您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/10/31 12:22:26发布147次查看
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泛型擦除问题及解决方法?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product