您好,欢迎访问一九零五行业门户网

如何避免Java泛型擦除问题及解决方法?

1、问题描述
泛型类型不能显式地运用在运行时类型的操作当中,例如:转型、instance of 和 new。因为在运行时,所有参数的类型信息都丢失了。
2、解决方法
/** * 泛型类型判断封装类 * @param <t> */class generictype<t>{    class<?> classtype;        public generictype(class<?> type) {        classtype=type;    }        public boolean isinstance(object object) {        return classtype.isinstance(object);    }}
在main方法我们可以这样调用:
generictype<a> generictype=new generictype<>(a.class);system.out.println(------------);system.out.println(generictype.isinstance(new a()));system.out.println(generictype.isinstance(new b()));
我们通过记录类型参数的class对象,然后通过这个class对象进行类型判断。
以上就是如何避免java泛型擦除问题及解决方法?的详细内容。
其它类似信息

推荐信息