I have a Class with generic type:
class Foo<T> {
protected boolean validateType(Object obj){
if (obj instanceof T) {
return true;
}
return false;
}
}
To test:
Foo foo = new Foo<String>();
foo.validateType(new String()); // should return true
foo.validateType(new Long()); // should return false;
And have a function that needs to validate an object against the generic type ‘T’, obviously the code above have errors?
How can I do such
What you are trying to do is not possible at it stands – generics are implemented in Java by erasure, which means that the generic parameter does not exist at runtime. It’s there for the compiler to typecheck, but at runtime there’s no way to tell the difference between a
Foo<String>and aFoo<Long>.So if you want a specific token to check against, you’ll have to do this yourself. A common pattern to do this sort of checking is to use
Classobject, with the benefit that these can be type-checked by the compiler:Note that your callers now need to pass in the
Classobject themselves; there’s no way around this requirement, it can’t be automatically wired in by Java itself.(Also, it’s a bad idea to use
if (x) return true; else return false;when it’s exactly the same asreturn x;but more confusing and error prone.)