views:

52

answers:

2

I have an interface

public interface FooBar<T> { }

I have a class that implements it

public class BarFoo implements FooBar<Person> { }

With reflection, I want to take an instance of BarFoo and get that the version of FooBar it implements is Person.

I use .getInterfaces from BarFoo to get back to FooBar, but that doesn't help me find out what T is.

+3  A: 

Try something like the following:

Class<T> thisClass = null;
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType = (ParameterizedType) type;
    Type[] typeArguments = parameterizedType.getActualTypeArguments();
    thisClass = (Class<T>) typeArguments[0];
}
matt b
GenericSuperClass != GenericInterface
BalusC
Close, but it didn't get me to the interface. BalusC had the missing link.
bwawok
ah missed the difference. Well, use this if you ever need the GenericSuperClass :)
matt b
+3  A: 

You can grab generic interfaces of a class by Class#getGenericInterfaces() which you then in turn check if it's a ParameterizedType and then grab the actual type arguments accordingly.

Type[] genericInterfaces = BarFoo.class.getGenericInterfaces();
for (Type genericInterface : genericInterfaces) {
    if (genericInterface instanceof ParameterizedType) {
        Type[] genericTypes = ((ParameterizedType) genericInterface).getActualTypeArguments();
        for (Type genericType : genericTypes) {
            System.out.println("Generic type: " + genericType);
        }
    }
}
BalusC
Great thanks! Casting to ParameterizedType helped
bwawok
You're welcome.
BalusC
Just be aware that this won't work if they define `BarFoo` as generic `BarFoo<T>` and then use `new BarFoo<Person>()`, even though that would be equivalent from "their" perspective.
Kevin Bourrillion
Yah. In this case this is my own code, and I am just doing reflection to test it. In my case they will all be declared at compile time.
bwawok