我有以下代码片段(这只是示例):
public class Class123 extends Thread implements Serializable, Runnable {
public <T extends String> T callFriend(String name, Class<T> type) {
return "";
}
}
有没有可能得到<T extends String> T
?
method.getGenericReturnType() == "T"
method.getReturnType().getName() == "java.lang.String"
我的第二个例子是:
public abstract class Function<T, R> {
public <V> Function<T, V> then(Function<? super R, ? extends V> after) {
return new Function<T, V>() {
@Override
public V apply(T t) {
return after.apply(Function.this.apply(t));
}
};
}
public abstract R apply(T t);
}
我想得到:<V> Function<T, V>
.
最佳答案
当你说你想要这个 <V> Function<T, V>
,那么这就是您要查找的内容(我想是这样,因为显然该类型已被删除)
Method andThen = Function.class.getDeclaredMethod("then", Function.class);
Type t = andThen.getGenericReturnType();
ParameterizedType claz= (ParameterizedType)t;
System.out.println(claz);
System.out.println(Arrays.asList(claz.getActualTypeArguments()));
它打印:
Function<T, V>
[T, V]
与您的第一个案例类似。举个例子,你也可以为变量而不仅仅是方法这样做:
class Outer{
//Aim is to capture the type of generic type below. i.e. String
List<String> ls = new ArrayList<String>();
}
Field field = Outer.class.getDeclaredField("ls");
ParameterizedType p = (ParameterizedType) field.getGenericType();
Class<?> claz = (Class<?>)p.getActualTypeArguments()[0];
System.out.println(claz);
// prints class java.lang.String
这也是一个class我为自己写的,在那里更容易捕获泛型类的类型。如果有帮助
关于java - 是否可以在反射的帮助下重建通用返回类型 - Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29986382/