I have an interface with generic
public interface MessageCallback<T extends JsonModel> {
void onMessage(T t);
}
And I wanna get instance of T. I found a solution where I can use reflection
public static <T> Class<T> getGenericClass(Class actualClass, int index) {
ParameterizedType genericSuperclass = (ParameterizedType) actualClass.getGenericSuperclass();
// Get generic class
return (Class<T>) genericSuperclass.getActualTypeArguments()[index];
}
But it throws exception.
java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
I wanna know is there a solution without using reflection?
Extra. I also found this
class Foo<T> {
final Class<T> typeParameterClass;
public Foo(Class<T> typeParameterClass) {
this.typeParameterClass = typeParameterClass;
}
public void bar() {
// you can access the typeParameterClass here and do whatever you like
}
}
But its only for class. How I can solve my problem? Thanks for your answers.
And if you wanna know it isn't clean Java. It's in Android