How do I cast a generic type T
into an object as Class<T>
?
Something like Class<T> T.class
or Class<T> T.getClass()
does not work, because T
is no variable.
A function should look like this:
public Class<T> getType() {
return // Class of T
}
Background info: I have some classes Class1<T>
, Class2<T>
, ... which all extend ParentClass<T>
. ParentClass
has the function getType()
. I'm looking for an more elegant way to get the type then just creating a variable Class<?> type
and saving the type that way.
You don't know T
at runtime (because of Type erasure).
Basically, MyWonderfulClass<String>
will become MyWonderfulClass<Object>
at runtime so you don't have any chance to retrieve it except if you directly give the class in the constructor or in a setter :
//class is a reserved keyword so I call it clazz instead.
public MyClass(Class<T> clazz) {
this.clazz = clazz;
}
public Class<T> getType() {
return this.clazz;
}
You can also force your subclasses to implement getType() : Class<T>
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments