Home  >  Article  >  Java  >  How to convert type erasure in java generics

How to convert type erasure in java generics

WBOY
WBOYforward
2023-04-18 23:40:01783browse

Explanation

1. Generic values ​​exist in the compilation phase. When the code enters the virtual machine, the generic values ​​will be deleted.

2. This feature is called type deletion. When generics are removed, he has two conversion methods. The first is that if the generic does not set a type upper limit, the generic will be converted to the Object type. The second is that if the type upper limit is set, the generic will be converted to its type upper limit.

Example

//未指定上限
public class Test1<T> {
    T t;
    public T getValue() {
        return t;
    }
    public void setVale(T t) {
        this.t = t;
    }
}
//指定上限
public class Test2<T extends String> {
    T t;
    public T getT() {
        return t;
    }
    public void setT(T t) {
        this.t = t;
    }
}
//通过反射调用获取他们的属性类型
@Test
public void testType1() {
    Test1<String> test1 = new Test1<>();
    test1.setVale("11111");
    Class<? extends Test1> aClass = test1.getClass();
    for (Field field : aClass.getDeclaredFields()) {
        System.out.println("Test1属性:" + field.getName() + "的类型为:" + field.getType().getName());
    }
 
    Test2 test2 = new Test2();
    test2.setT("2222");
    Class<? extends Test2> aClass2 = test2.getClass();
    for (Field field : aClass2.getDeclaredFields()) {
        System.out.println("test2属性:" + field.getName() + "的类型为:" + field.getType().getName());
    }
}

The above is the detailed content of How to convert type erasure in java generics. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete