是否可以借助反射-Java重构泛型返回类型?

是否可以借助反射-Java重构泛型返回类型?,java,generics,reflection,types,Java,Generics,Reflection,Types,我有以下代码片段(仅为示例): 我的第二个例子是: public abstract class Function<T, R> { public <V> Function<T, V> then(Function<? super R, ? extends V> after) { return new Function<T, V>() { @Override publi

我有以下代码片段(仅为示例):

我的第二个例子是:

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);
}
公共抽象类函数{

然后是公共函数(函数当你说你想要这个
函数
,那么这就是你想要的(我想是这样的,因为很明显类型被删除了)

它打印:

Function<T, V> 
[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
类外部{
//目的是捕获下面的泛型类型,即字符串
List ls=新的ArrayList();
}
Field=Outer.class.getDeclaredField(“ls”);
ParameteredType p=(ParameteredType)字段。getGenericType();
类claz=(类)p.getActualTypeArguments()[0];
系统输出打印LN(claz);
//打印类java.lang.String

这也是我为自己写的一篇文章,在这里更容易捕获泛型类的类型。如果你说你想要这个
函数,它会有帮助,那么这就是你想要的(我想是这样,因为类型显然会被删除)

它打印:

Function<T, V> 
[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
类外部{
//目的是捕获下面的泛型类型,即字符串
List ls=新的ArrayList();
}
Field=Outer.class.getDeclaredField(“ls”);
ParameteredType p=(ParameteredType)字段。getGenericType();
类claz=(类)p.getActualTypeArguments()[0];
系统输出打印LN(claz);
//打印类java.lang.String

另外,这是我为自己编写的一个,在这里更容易捕获泛型类的类型。如果它有帮助,因为
String
final
,我不认为
t extends String
将是一个特别有用的类型参数。@DavidWallace,你是对的。但是,这只是一个示例。我只想获得泛型返回类型和类型定义。然后,也许您可以构造一个更好地反映您试图实现的目标的示例。现在,您似乎正在尝试找出
的类
,无论发生什么,它始终是
String
。@DavidWallace,我已经添加了。由于
String
final
,我不认为
t extends String
将是一个特别有用的类型参数。@DavidWallace,你是对的。但是,这只是一个示例。我只想获得泛型返回类型和类型定义n也许你可以构造一个更好地反映你试图实现的目标的示例。现在,你似乎在试图找出
”的类,它将始终是
String
,无论发生什么。@DavidWallace,我已经添加了。
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