Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA - Get generic implementation of a class

Tags:

java

generics

Imagine I have an abstract class defining a Generic Type. All subclasses will implement this Generic Type.

I can achive so by declaring a abstract method that forces the subclass to return that type. But is there a more elegant way to achieve this directly from the 'Class' object definition of the subclass?

public class GenericTest {
    public static void main(String[]args) throws Exception{
        Class strClass = ClazzImplString.class;
        Class intClass = ClazzImplInteger.class;

        Class implTypeStr = ((AbsClazz)strClass.getConstructor().newInstance()).getGenericType();
        Class implTypeInt = ((AbsClazz)intClass.getConstructor().newInstance()).getGenericType();

        System.out.println("implTypeStr: " + implTypeStr);
        System.out.println("implTypeInt: " + implTypeInt);
    } 
}
abstract class AbsClazz<GenericType> {
    abstract Class getGenericType();
}

class ClazzImplString extends AbsClazz<String> {
    public ClazzImplString() {}    
    @Override  Class getGenericType() {return String.class;}
}
class ClazzImplInteger extends AbsClazz<Integer> {
    public ClazzImplInteger() {}    
    @Override Class getGenericType() {return Integer.class;}
}

Thank you in advance

like image 931
Netto Avatar asked Dec 12 '22 01:12

Netto


1 Answers

Yes, you can use reflection.

ParameterizedType genericSuperclass = (ParameterizedType) ClazzImplString.class.getGenericSuperclass();
Class<?> clazz = (Class<?>) genericSuperclass.getActualTypeArguments()[0];
System.out.println(clazz); // prints class java.lang.String
like image 189
Sotirios Delimanolis Avatar answered Dec 13 '22 15:12

Sotirios Delimanolis