[英]How to get Generic Return type of a method using Reflections
有沒有辦法獲得泛型方法的返回類型 - 返回類型?
public interface MyGeneric<T> {
T doSomething();
}
public interface MyElement extends MyGeneric<Element> {
}
public class Main {
public static final void main(String[] args) {
System.out.println(MyElement.class.getMethod("doSomething", new Class<?>[0]).magic()); // => Element
}
}
使用Method.getReturnType()我得到java.lang.Object沒有。 方法“魔法”是否存在?
不幸的是,核心Java庫中的反射功能對於分析泛型類型來說相當差。 您可以使用getGeneric...
方法(例如, getGenericReturnType()
),但它們不能很好地工作,並且它們通常返回Type
實例而不是Class
實例。 我發現這非常笨拙。
我已經編寫了自己的反射API,基於.NET,我覺得它更一致(特別是在涉及泛型的地方)。 考慮以下輸出:
import com.strobel.reflection.Type;
interface MyGeneric<T> {
T doSomething();
}
interface Element {}
interface MyElement extends MyGeneric<Element> {}
class Main {
public static final void main(String[] args) throws NoSuchMethodException {
// prints "class java.lang.Object":
System.out.println(
MyElement.class.getMethod("doSomething").getReturnType()
);
// prints "T":
System.out.println(
MyElement.class.getMethod("doSomething").getGenericReturnType()
);
// prints "Element":
System.out.println(
Type.of(MyElement.class).getMethod("doSomething").getReturnType()
);
}
}
歡迎您使用我的圖書館 。 我實際上只是提交了一個錯誤修復程序,阻止了這個例子的工作(它位於develop
分支的頂端)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.