获取继承的泛型方法的返回类型 [英] Get the return Type for inherited generic method
本文介绍了获取继承的泛型方法的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这3个班级
public class Box<O> {
public O getItem() {...}
}
public class CoolBox extends Box<Integer> { ... }
public class AmazingBox extends CoolBox { ... }
在代码的某一时刻,我需要获取AmazingBox
类的方法getItem()
的返回类型,但是当通过反射访问其方法时,我将Object
作为返回类型而不是Integer
.
At one point in my code, I need to get the return Type of the method getItem()
for the AmazingBox
class, but when accessing its methods via reflection, I get Object
as the return Type instead of Integer
.
有什么方法(纯Java或其他库)获取Integer
作为返回类型?
Is there any way, (plain java or extra libraries) to get Integer
as the return Type?
这是我用来获取返回类型的代码:
This is the code I used to get the return type:
Class<?> c = AmazingBox.class; // This is not how i get the class but its for demonstration purposes
Method m = c.getMethod("getItem");
Type t = m.getReturnType();
推荐答案
我刚刚发现有一个名为 GenericsResolver 正是我想要的.
I just discovered that there is a library called GenericsResolver that does exactly what I want.
使用这段代码可以返回正确的类型
Using this piece of code it returns the correct type
Class<?> clazz = AmazingBox.class;
GenericsContext genericsContext = GenericsResolver.resolve(clazz);
Method method = clazz.getMethod("getItem");
Type methodReturnType = genericsContext.method(method).resolveReturnType();
这篇关于获取继承的泛型方法的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文