Java 如何使用反射获取方法的通用返回类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19906614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Generic Return type of a method using Reflections
提问by mibutec
Is there a way get the return type of a generic method- return type?
有没有办法获取泛型方法的返回类型 - 返回类型?
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
}
}
Using Method.getReturnType() I get java.lang.Object without. Does the method "magic" exist?
使用 Method.getReturnType() 我得到 java.lang.Object 没有。方法“魔法”存在吗?
回答by Andrei I
No, that magic does not exist generally. If you want to make a trick in order to get to that data, you can require that data in your interface like explained here.
不,那种魔法一般不存在。如果您想通过技巧来获取该数据,您可以像此处解释的那样在您的界面中要求该数据。
On the other side, if your type is special (like a List), you can do that. See this answerfor special types.
另一方面,如果您的类型很特殊(如 List),您可以这样做。有关特殊类型,请参阅此答案。
回答by Mike Strobel
Unfortunately, the reflection capabilities in the core Java library are rather poor for analyzing generic types. You can use the getGeneric...
methods (e.g., getGenericReturnType()
), but they don't work all that well, and they usually return Type
instances instead of Class
instances. I find this very clumsy to work with.
不幸的是,核心 Java 库中的反射能力对于分析泛型类型来说相当差。您可以使用这些getGeneric...
方法(例如,getGenericReturnType()
),但它们并不能很好地工作,并且它们通常返回Type
实例而不是Class
实例。我觉得这很笨拙。
I have written my own reflection API, based the .NET's, which I feel is more consistent (particularly where generics are concerned). Consider the following output:
我已经基于 .NET 编写了自己的反射 API,我觉得它更一致(特别是在涉及泛型的地方)。考虑以下输出:
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()
);
}
}
You're welcome to use my library. I actually just committed a bug fix that prevented this example from working (it's in the tip of the develop
branch).
欢迎您使用我的图书馆。我实际上只是提交了一个错误修复,阻止了这个例子的工作(它在develop
分支的顶端)。