2012-07-30 63 views
2

尼尔Gafter介绍type tokens(例如Class<String>)。假设在运行时可以访问Class<String>的实例,是否可以在运行时检索通用类型(String)?是否可以在运行时检索用于类型令牌的通用类型(即类别<T>)?

我在寻找类似于Method.getGenericReturnType()的东西。

+1

不知道你的意思。如果你已经有了Class实例,你还想要什么? – jtahlborn 2012-07-30 18:19:34

+0

用作通用参数的类型。 – JVerstry 2012-07-30 18:28:51

+1

_what_?一个类实例或某个类型的名字?也许你可以添加一些伪代码,说明你正在寻找什么...... – jtahlborn 2012-07-30 18:41:25

回答

0

有可能使用Gafter的小工具模式的鲍勃·李的阐述的变化:

public class GenericTypeReference<T> { 

    private final Type type; 

    protected GenericTypeReference() { 
     Type superclass = getClass().getGenericSuperclass(); 
     if (superclass instanceof Class) { 
      throw new RuntimeException("Missing type parameter."); 
     } 
     this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0]; 
    } 

    public Type getType() { 
     return this.type; 
    } 

    public static void main(String[] args) { 

     // This is necessary to create a Class<String> instance 
     GenericTypeReference<Class<String>> tr = 
      new GenericTypeReference<Class<String>>() {}; 

     // Retrieving the Class<String> instance 
     Type c = tr.getType(); 

     System.out.println(c); 
     System.out.println(getGenericType(c)); 

    } 

    public static Type getGenericType(Type c) { 
     return ((ParameterizedType) c).getActualTypeArguments()[0]; 
    } 

} 

上面的代码打印:

java.lang.Class<java.lang.String> 
class java.lang.String 
2

我认为它只适用于字段/方法。由于类型擦除,我们无法在运行时获得类特定的泛型类型。如果你有上课的机会,你似乎可以进行破解。阅读discussion

+0

+1提及删除类型。 – 2012-07-30 18:22:49

+0

实际上,只要它是类型声明的一部分,就可以在运行时检索类型信息。这就是黑客所指的...... – Jonathan 2012-07-30 21:31:18

+0

嗯,我找到了一个解决方案...所以它也可能是类! – JVerstry 2012-07-30 21:39:17

1

与C#不同,泛型在Java中的运行时不存在。因此,您不能尝试创建泛型类型的实例,或尝试在运行时查找泛型类型。

+1

错误,通用信息可用作元数据,否则,Method.getGenericReturnType()如何工作? – JVerstry 2012-07-30 18:27:37

+1

我正在谈论一些泛型类型T,并且你正在讨论带有泛型类型T的参数或返回类型的方法。 – 2012-07-30 18:38:24

+0

是的,没错。他们是一样的。 – JVerstry 2012-07-30 18:41:30

1

这听起来像你想要的是ParameterizedType

您通过反思Class和来自它的物体(Method,Field)得到这些结果。但是,您无法从任何旧的Class对象获取ParameterizedType;您可以从代表扩展泛型类或接口的类型的Class实例中获得一个实例。

+0

好的,但那么,如何专门进行? – JVerstry 2012-07-30 21:37:07