簡體   English   中英

如何使用Reflection獲取方法的Generic Return類型

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM