避免Java类型擦除 [英] Avoiding Java Type Erasure

查看:131
本文介绍了避免Java类型擦除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法可以避免类型擦除和访问类型参数?

  public class Foo< T extends枚举<?> &安培;酒吧及GT; {
public Foo(){
//在这里访问模板类?
//即:
baz(T.class); //显然不起作用


private void baz(Class< T> qux){
//做类似
的东西T [] constants = qux .getEnumConstants();
...
}
}

我需要知道关于 T ,并且做它。是否有可能,如果是这样,如何在没有的情况下在构造函数中或除参数外的任何地方传递

<编辑:这个问题的主要目的是要找出围绕类型擦除是否存在任何实际的方式

解决方案

AFACT,围绕类型擦除存在 no 实用方法,因为您不能要求运行时无法访问的内容。假设当然你同意为每个实现 Bar 接口的枚举子类化泛型类是一个实际的工作。

  enum Test实现Bar {
一个,两个
}

class Foo< T>扩展FooAbstract< Test> {
public Foo(){
ParameterizedType genericSuperclass =
(ParameterizedType)getClass()。getGenericSuperclass(); $(b)baz((Class< T>)genericSuperclass.getActualTypeArguments()[0]);


private void baz(Class< T> qux){
T [] constants = qux.getEnumConstants();
System.out.println(Arrays.toString(constants)); // print [ONE,TWO]
}
}

interface Bar {
}

class FooAbstract< T扩展Enum< > &安培;酒吧及GT; {
}


Is there a way one could avoid type erasure and get access to a type parameter?

public class Foo<T extends Enum<?> & Bar> {
    public Foo() {
        // access the template class here?
        // i.e. :
        baz(T.class); // obviously doesn't work
    }

    private void baz(Class<T> qux) { 
        // do stuff like
        T[] constants = qux.getEnumConstants();
        ...
    } 
}

I need to know about T, and do things with it. Is it possible, and if so, how can it be done without passing in the class in the constructor or anywhere besides the parameter?

EDIT: The main purpose of this question is to find out if there is any practical way around type erasure.

解决方案

AFACT, there is no practical way around type erasure because you can't ask for something which the runtime doesn't have access to. Assuming of course you agree that sub-classing generic classes for each enum which implements Bar interface is a practical work around.

enum Test implements Bar {
    ONE, TWO
}

class Foo<T> extends FooAbstract<Test> {
    public Foo() {
        ParameterizedType genericSuperclass =
                (ParameterizedType) getClass().getGenericSuperclass();
        baz((Class<T>) genericSuperclass.getActualTypeArguments()[0]);
    }

    private void baz(Class<T> qux) {
        T[] constants = qux.getEnumConstants();
        System.out.println(Arrays.toString(constants)); // print [ONE, TWO]
    }
}

interface Bar {
}

class FooAbstract<T extends Enum<?> & Bar> {
}

这篇关于避免Java类型擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆