
1、问题描述
泛型类型不能显式地运用在运行时类型的操作当中,例如:转型、instance of 和 new。因为在运行时,所有参数的类型信息都丢失了。
2、解决方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class GenericType<T>{
Class<?> classType;
public GenericType(Class<?> type) {
classType=type;
}
public boolean isInstance(Object object) {
return classType.isInstance(object);
}
}
|
在main方法我们可以这样调用:
1 2 3 4 | 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泛型擦除的问题解决,希望对大家有所帮助。更多Java学习指路:Java基础
本教程操作环境:windows7系统、java10版,DELL G3电脑。