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

How to convert type erasure in java generics

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-04-18 23:40:01
forward
907 people have browsed it

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

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!

Related labels:
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
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template