Thursday, February 20, 2020

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()
                .getGenericSuperclass()).getActualTypeArguments()[0]).getTypeName();
    }
}
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();
        System.out.println(getTypeChild.getGenericName());
    }
}
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.

Reference:
Previous Post
Next Post

0 komentar: