I have a generics class, Foo
. In a method of Foo
, I want to get the class instance of type T
, but I just can\'t call T.
As explained in other answers, to use this ParameterizedType
approach, you need to extend the class, but that seems like extra work to make a whole new class that extends it...
So, making the class abstract it forces you to extend it, thus satisfying the subclassing requirement. (using lombok's @Getter).
@Getter
public abstract class ConfigurationDefinition {
private Class type;
...
public ConfigurationDefinition(...) {
this.type = (Class) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
...
}
}
Now to extend it without defining a new class. (Note the {} on the end... extended, but don't overwrite anything - unless you want to).
private ConfigurationDefinition myConfigA = new ConfigurationDefinition(...){};
private ConfigurationDefinition myConfigB = new ConfigurationDefinition(...){};
...
Class stringType = myConfigA.getType();
Class fileType = myConfigB.getType();