Java泛型无界类型擦除

Java泛型无界类型擦除

如果使用无界类型参数,则Java编译器将使用Object替换类型参数。

示例

创建一个名称为:UnboundedTypesErasure.java 文件,并编写以下代码 -

package com.zyiz.demo2;

public class UnboundedTypesErasure {
    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        Box<String> stringBox = new Box<String>();

        integerBox.add(new Integer(1000));
        stringBox.add(new String("Hello World"));

        System.out.printf("Integer Value :%d\n", integerBox.get());
        System.out.printf("String Value :%s\n", stringBox.get());
    }
}

class Box<T> {
    private T t;

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

在本示例中,java编译器将用Object类替换T,而在类型擦除之后,编译器会为以下代码生成字节码。

package com.zyiz.demo2;

public class UnboundedTypesErasure {
    public static void main(String[] args) {
        Box integerBox = new Box();
        Box stringBox = new Box();

        integerBox.add(new Integer(1000));
        stringBox.add(new String("Hello World"));

        System.out.printf("Integer Value :%d\n", integerBox.get());
        System.out.printf("String Value :%s\n", stringBox.get());
    }
}

class Box {
    private Object t;

    public void add(Object t) {
        this.t = t;
    }

    public Object get() {
        return t;
    }
}

在这两种情况下,执行输出结果是相同的 -

Integer Value :1000
String Value :Hello World