是否可以访问以下行中的通用参数?
public List<StoryLikeRef> getLikes() throws IOException
我的意思是通过反射从返回类型中获取 StoryLikeRef ?
谢谢
最佳答案
是的,可以,假设 StoryLikeRef 是具体类型(而不是类型参数本身)。使用Method.getGenericReturnType
获取类型
。示例代码:
import java.lang.reflect.*;
import java.util.*;
public class Test {
public List<String> getStringList() {
return null;
}
public List<Integer> getIntegerList() {
return null;
}
public static void main(String[] args) throws Exception {
showTypeParameters("getStringList");
showTypeParameters("getIntegerList");
}
// Only using throws Exception for sample code. Don't do
// this in real life.
private static void showTypeParameters(String methodName)
throws Exception {
Method method = Test.class.getMethod(methodName);
Type returnType = method.getGenericReturnType();
System.out.println("Overall return type: " + returnType);
if (returnType instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) returnType;
for (Type t: type.getActualTypeArguments()) {
System.out.println(" Type parameter: " + t);
}
} else {
System.out.println("Not a generic type");
}
}
}
关于java - 访问返回类型的泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6938858/