![](/img/trans.png)
[英]Reflection can't get the actual parameter type of a method that overrides from a generic-typed interface?
[英]Actual type of generic interface method parameter
涉及實施課程時我已經回答了這個問題(我沒有),但這些方法對我不起作用。
假設我有一個界面
public interface MySuperInterface<T> {
public void test(T arg);
}
然后是擴展接口
public interface MyInterface extends MySuperInterface<String> {
}
如果我正在迭代MyInterface類的方法,是否可以從MyInterface類中獲取'test'方法的參數的實際類型(在本例中為String)?
for (Method method : MyInterface.class.getMethods())
{
for (Parameter parameter : method.getParameters())
{
final Class<?> paramClass = parameter.getType();
System.out.println(paramClass);
}
}
上面的代碼將輸出'class java.lang.Object'。 我不應該告訴參數將是一個字符串嗎?
如果你有明確提供類型參數的實現接口,那么這可以通過反射實現; 使用的以下類型是從java.lang.reflect
導入的。
首先獲取與第一個超級接口對應的Type
對象。
Type tmi = MyInterface.class.getGenericInterfaces()[0];
在這種情況下, tmi
實際上是ParameterizedType
, Type
的子接口。 拋出它並得到它的類型參數。
ParameterizedType ptmi = (ParameterizedType) tmi;
Type typeArg = ptmi.getActualTypeArguments()[0];
因為您提供了類名作為類型參數而不是其他參數化類型或其他類型參數,所以typeArg
是一個實現Type
的Class
。 在這里,它是java.lang.Class
。
System.out.println(typeArg);
class java.lang.String
您可以使用我的實用程序類GenericUtil
。 它可以解析泛型類型。
Method m = MyInterface.class.getMethod("test", Object.class); // get the method
Type p = m.getGenericParameterTypes()[0]; // get the generic type 'T'
Map<TypeVariable<?>, Type> map = GenericUtil.getGenericReferenceMap(MyInterface.class); // get generic map of the class's context
System.out.println(map.get(p)); // get actual type for 'T'
產量
class java.lang.String
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.