我正在使用反射来获取类中的所有方法,如下所示:
Method[] allMethods = c.getDeclaredMethods();
之后我将迭代这些方法
for (Method m: allMethods){
//I want to find out if the return is is a parameterized type or not
m.getReturnType();
}
例如:如果我有这样的方法:
public Set<Cat> getCats();
如何使用反射来找出包含 Cat
作为参数化类型的返回类型?
最佳答案
你试过吗getGenericReturnType()
?
Returns a
Type
object that represents the formal return type of the method represented by thisMethod
object.If the return type is a parameterized type, the
Type
object returned must accurately reflect the actual type parameters used in the source code.If the return type is a type variable or a parameterized type, it is created. Otherwise, it is resolved.
然后(从Javadocs来看),似乎你必须将其转换为 ParameterizedType
并调用getActualTypeArguments()
就在上面。
这里是一些示例代码:
for (Method m : allMethods) {
Type t = m.getGenericReturnType();
if (t instanceof ParameterizedType) {
System.out.println(t); // "java.util.Set<yourpackage.Cat>"
for (Type arg : ((ParameterizedType)t).getActualTypeArguments()) {
System.out.println(arg); // "class yourpackage.Cat"
}
}
}
关于java - 如何通过检查找到返回类型的参数化类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1213735/