Home >Java >javaTutorial >How to avoid Java generic erasure problems and solutions?
1. Problem description
Generic types cannot be explicitly used in runtime type operations, such as transformation, instance of and new. Because at run time, the type information of all parameters is lost.
2. Solution
/** * 泛型类型判断封装类 * @param <T> */ class GenericType<T>{ Class<?> classType; public GenericType(Class<?> type) { classType=type; } public boolean isInstance(Object object) { return classType.isInstance(object); } }
In the main method we can call it like this:
GenericType<A> genericType=new GenericType<>(A.class); System.out.println("------------"); System.out.println(genericType.isInstance(new A())); System.out.println(genericType.isInstance(new B()));
We record the Class object of the type parameter, Then perform type judgment through this Class object.
The above is the detailed content of How to avoid Java generic erasure problems and solutions?. For more information, please follow other related articles on the PHP Chinese website!