I have a class with a collection getter that I'm inspecting via reflection. Something like this:
class Bar {
String baz;
int bazooka;
}
class Foo {
List<Bar> bars = new ArrayList<Bar>();
List<Bar> getBarsList() { return bars; }
}
What I need to find out at runtime is the class object Class<Bar>
. I know it's possible if you have a reference to the Field
object. But is it also possible from the getter Method
?
In your case it is possible using reflection. What you can't do is get runtime information about types. Given an instance of a parametrized type, you can't at runtime find out what that was parametrized with. This is what the other answers are telling you, but that's not what you're asking. You're asking about compile time type constraints.
public class Test {
public static void main(String args[]) throws NoSuchMethodException {
Method method = Foo.class.getDeclaredMethod("getBars", new Class[]{});
Type grt = method.getGenericReturnType();
if (grt instanceof ParameterizedType) {
Type Bar = ((ParameterizedType) grt).getActualTypeArguments()[0];
System.out.println(Bar);
}
}
}
class Foo {
List<Bar> getBars() {
return Collections.emptyList();
}
}
class Bar {
}
Prints class com.package.Bar
If on the other hand you had a class like this:
class Foo<T> {
List<T> getBars() {
return Collections.emptyList();
}
}
Then you could not get T for instances of Foo at runtime. There exists workarounds, where people create anonymous subclasses with the type parameter fixed.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments