Home > Java > javaTutorial > body text

How to avoid Java generic erasure problems and solutions?

WBOY
Release: 2023-04-23 12:22:07
forward
1002 people have browsed it

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);
    }
}
Copy after login

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()));
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template