Java generics question - Class<T> vs. T? -
i'm using hibernate validator , trying create little util class:
public class datarecordvalidator<t> {     public void validate(class<t> clazz, t validateme) {         classvalidator<t> validator = new classvalidator<t>(clazz);         invalidvalue[] errors = validator.getinvalidvalues(validateme);         [...]     } }   question is, why need supply class<t> clazz parameter when executing new classvalidator<t>(clazz)?  why can't specify:
tinclassvalidator<t>(t)?validateme.getclass()inclassvalidator<t>(validateme.getclass())
i errors when try both options.
edit: understand why #1 doesn't work. don't why #2 doesn't work. error #2:
cannot find symbol symbol  : constructor classvalidator(java.lang.class<capture#279 of ? extends java.lang.object>) location: class org.hibernate.validator.classvalidator<t>   note: hibernate api method (here)
if validate method yours, can safely skip class atribute.
public void validate(t validateme) {     classvalidator<t> validator =             new classvalidator<t>((class<t>) validateme.getclass());     ... }   but classvalidator constructor requires class argument.
using unsafe cast not preferred, in case safe if don't have this:
class {..} class b extends {..}  new datarecordvalidator<a>.validate(new b());   if think need that, include class argument in method. otherwise may getting classcastexception @ runtime, debuggable, although it's not quite idea behind generics.
Comments
Post a Comment