I’m using Hibernate validator and trying to create a 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 do I need to supply the Class<T> clazz parameter when executing new ClassValidator<T>(clazz)? Why can’t you specify:
Tas inClassValidator<T>(T)?validateMe.getClass()as inClassValidator<T>(validateMe.getClass())
I get errors when I try to do both options.
Edit: I understand why #1 doesn’t work. But I don’t get why #2 doesn’t work. I currently get this error with #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 is (here)
If the
validatemethod is yours, then you can safely skip theClassatribute.But the
ClassValidatorconstructor requires aClassargument.Using an unsafe cast is not preferred, but in this case it is actually safe if you don’t have something like this:
If you think you will need to do something like that, include the
Classargument in the method. Otherwise you may be gettingClassCastExceptionat runtime, but this is easily debuggable, although it’s not quite the idea behind generics.