【问题标题】:Getting raw class from a type erased Java object从类型擦除的 Java 对象中获取原始类
【发布时间】:2014-08-04 10:29:08
【问题描述】:

我有一个对象,我需要获取该对象的Type。我需要从已擦除的对象中获取 rawType。

例如我有一个班级

class Blah{}

class Dummy extends Blah{}

class A<T extends Blah>
{
}

i create a instance for A like this new A<Dummy>().

我需要获取创建对象的原始类型,我看到 Apache 有 TypeUtils getRawClass。但它需要一个 java 类型。我有实际的实例,但我如何从中获取类型。做 object.getClass() 似乎没有帮助,原始类型也没有恢复。不胜感激。

编辑: 感谢您的回复,就像下面的答案一样,它找不到任何获取实际类型的方法。保留该类型的唯一建议是使用超类型标记。 http://gafter.blogspot.com/2006/12/super-type-tokens.html

【问题讨论】:

  • 这个A.class.getTypeParameters()[0].getBounds()[0] 将返回Blah

标签: java generics type-erasure raw-types


【解决方案1】:

我有实际的实例,但我如何从中获取类型

由于泛型类型擦除,这是不可能的。

在运行时,实例没有其泛型类型的记录。

更多讨论请参见other thread

【讨论】:

  • 所以在你的例子中,反射可以给你Blah(编译时类型),但不能给你Dummy(运行时类型,当然扩展Blah)。
【解决方案2】:

正如@Thilo 所建议的,通用信息在编译时可用。如果需要,则必须将其存储在对象本身的某个位置。

示例代码:

class A<T extends Blah> {

    private Class<T> type;

    public A(Class<T> type) { // class must be exactly same as type of object
        this.type = type;
    }

    public Class<T> getType() {
        return type;
    }
}

...

A<Dummy> a = new A<Dummy>(Dummy.class); // only Dummy.class is the valid argument
System.out.println(a.getType().getName());   // com.x.y.z.Dummy

...
A<Dummy> a = new A<Dummy>(Blah.class); // not valid, compile time error
A<Dummy> a = new A<Dummy>(Dummy2.class); // not valid, compile time error
A<Dummy> a = new A<Dummy>(XYZ.class); // not valid, compile time error

【讨论】:

    猜你喜欢
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    相关资源
    最近更新 更多