
1、问题描述
泛型类型不能显式地运用在运行时类型的操作当中,例如:转型、instance of 和 new。因为在运行时,所有参数的类型信息都丢失了。
2、解决方法
/**
*泛型类型判断封装类
*@param<T>
*/
classGenericType<T>{
Class<?>classType;
publicGenericType(Class<?>type){
classType=type;
}
publicbooleanisInstance(Objectobject){
returnclassType.isInstance(object);
}
}
在main方法我们可以这样调用:
GenericType<A>genericType=newGenericType<>(A.class);
System.out.println("------------");
System.out.println(genericType.isInstance(newA()));
System.out.println(genericType.isInstance(newB()));
我们通过记录类型参数的Class对象,然后通过这个Class对象进行类型判断。
以上就是Java泛型擦除的问题解决,希望对大家有所帮助。更多Java学习指路:Java基础
原文来自:https://www.py.cn© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END


















































暂无评论内容