jeudi 8 janvier 2015

How to determine generic parameter of one of implemented interfaces?

I would like to have generic tagging interface, so that tag contain some class information.


Now, how to know with which class the given tag was parametrized with?


In the code below I am taking an object, then looking for tag MyClass2 and then wishing to extract the parameter of the tag (which is MyClass3)



package tests.java;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Try_GenericRuntime {

public static class MyClass1 implements MyClass2<MyClass3>, MyClass4<MyClass5 >{
}

interface MyClass2<T> {
}

interface MyClass4<T> {
}

interface MyClass3 {
}

interface MyClass5 {
}

@SuppressWarnings("unchecked")
public static void main(String[] args) {


MyClass1 a = new MyClass1();

// how to derive/reach MyClass3?

Type[] ifaces = a.getClass().getGenericInterfaces();

Type iface;

Type[] params;

for(int i=0; i<ifaces.length; ++i) {
iface = ifaces[i];
if( ((Class)iface).isAssignableFrom(MyClass2.class) ) {
params = ((ParameterizedType)iface).getActualTypeArguments();
System.out.println(params[0].toString());
}
}

}
}


This code gives sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl cannot be cast to java.lang.Class exception message.


Other variants are also problematic due to incompatibilities between ParameterizedType and Class.






Aucun commentaire:

Enregistrer un commentaire