Reputation: 1029
I have some interface with generic type interface DummyInterface<T>
and i have class to which i have to set interface
class DummyClass<T>{
public void setDummyInterface(DummyInterface<T> dummyInterface){
//set interface
}
}
Imagine the situation where i store DummyClass
with different generics in ArrayList
. When i get class from list i don't know the generic of class, and i want to check if interface has the same generic or not;
For example i want to check like this
if(dummyInterface<SomeTypeIKnow>.getGenericType() == dummyClass.getGenericType()){
dummyClass.setDummyInterface(dummyInterface);
}
Upvotes: 0
Views: 72
Reputation: 5107
You can use something like TypeTools (a library that I authored) to resolve type arguments so long as the argument is captured in a type definition. For example:
interface DummyStringInterface extends DummyInterface<String> {}
Class<?> t = TypeResolver.resolveRawArgument(DummyInterface.class, DummyStringInterface.class);
assert t == String.class;
Upvotes: 1
Reputation: 28294
Not entirely sure I understand your question, but this code will allow you to get the Generic types for an object. They allow you to perform reflection on the generic parameters of an object.
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class GenericClassUtils {
public static <T> Class<T> getClassFromGeneric(
Object parentObj,
int oridnalParamterizedTypeIndex) throws Exception{
Type[] typeArray = getParameterizedTypeListAsArray(parentObj);
return (Class<T>)typeArray[oridnalParamterizedTypeIndex];
}
public static <T> Type[] getParameterizedTypeListAsArray(Object parentObj){
return ((ParameterizedType) parentObj.getClass()
.getGenericSuperclass())
.getActualTypeArguments();
}
}
Perhaps by calling something like this:
Class clazz = getClassFromGeneric(dummyClass, 0);
if (clazz.isInstance(SomeTypeIKnow.class)){
dummyClass.setDummyInterface(dummyInterface);
}
Upvotes: 1