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); }
Advertisement
Answer
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;