开发者

Accessing Type Parameters Using Reflection

开发者 https://www.devze.com 2023-02-02 08:26 出处:网络
How do I find type parameter values passed to a super class using reflection? For example, given Bar开发者_高级运维.class, how do I find that it passes Integer.class to Foo\'s type parameter T?

How do I find type parameter values passed to a super class using reflection?

For example, given Bar开发者_高级运维.class, how do I find that it passes Integer.class to Foo's type parameter T?

public class Foo<T> {
}

public class Bar extends Foo<Integer> {
}

Thanks!


You can try

ParameterizedType type = (ParameterizedType) Bar.class.getGenericSuperclass();
System.out.println(type.getRawType()); // prints; class Foo
Type[] actualTypeArguments = type.getActualTypeArguments();
System.out.println(actualTypeArguments[0]); // prints; class java.lang.Integer

This only works because Bar is a class which extends a specific Foo. If you declared a variable like the following, you wouldn't be able to determine the parameter type of intFoo at runtime.

Foo<Integer> intFoo = new Foo<Integer>();


public class Bar extends Foo<Integer> {

 public Class getTypeClass {
   ParameterizedType parameterizedType =
     (ParameterizedType) getClass().getGenericSuperClass();
  return (Class) parameterizedtype.getActualTypeArguments()[0];
 }

}

The given above should work in most of the practical situations,but not guaranteed, because of type erasure, there is no way to do this directly.

0

精彩评论

暂无评论...
验证码 换一张
取 消