我有一個接口如何獲得具體類型的通用接口的
public interface FooBar<T> { }
我有一個實現它
public class BarFoo implements FooBar<Person> { }
與反思,我要帶BarFoo的實例類並得到它實現的FooBar版本是Person。
我使用BarFoo的.getInterfaces
返回到FooBar,但這並不能幫助我找出T是什麼。
我有一個接口如何獲得具體類型的通用接口的
public interface FooBar<T> { }
我有一個實現它
public class BarFoo implements FooBar<Person> { }
與反思,我要帶BarFoo的實例類並得到它實現的FooBar版本是Person。
我使用BarFoo的.getInterfaces
返回到FooBar,但這並不能幫助我找出T是什麼。
您可以通過Class#getGenericInterfaces()
搶一類的通用接口,你再依次檢查,如果它是一個ParameterizedType
,然後搶actual type arguments相應。
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);
}
}
}
嘗試類似如下:
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];
}
非常感謝!投射到參數化類型幫助 – bwawok 2010-07-14 14:34:01
不客氣。 – BalusC 2010-07-14 14:48:12
請注意,如果他們將BarFoo定義爲通用的BarFoo然後使用新的BarFoo (),那麼這將不起作用,即使這與「他們」的觀點相同。 –
2010-07-14 15:23:50