Get Class Name from Generic Java Class

You can get the name of the generics from the subclass. See this example. We Define a parent class like this:
public class GetTypeParent<T> {
protected String getGenericName() {
return ((Class<T>) ((ParameterizedType) getClass()
We then define its child class in this way:
public class GetTypeChild extends GetTypeParent<Integer> {
public static void main(String[] args) {
GetTypeChild getTypeChild = new GetTypeChild();
You can see that in the main method, or in any instance method, I am capable to get the name of the generics type, in this case the main will print: java.lang.Integer.


Post a Comment

Mới hơn Cũ hơn