15.8 擦除的补偿

  • new T() 无法实现,因为擦除,还因为不确定T有无参构造函数;
package chapter15._8;

public class Erased {

    private final int SIZE = 100;

    public static void f(Object arg) {
        // if (arg instanceof T) {} // error
        // T var = new T(); // error
        // T[] array = new T[SIZE]; // error
        // T[] array = (T)new Object[SIZE]; // error
    }

}

package chapter15._8;

class Building {}
class House extends Building {}

public class ClassTypeCapture {

    // 类型标签
    Class kind;

    public ClassTypeCapture(Class kind) {
        this.kind = kind;
    }

    public boolean f(Object arg) {
        // 如果arg可以转型成kind,返回true
        return kind.isInstance(arg);
    }

    public static void main(String[] args) {
        ClassTypeCapture ctt1 = new ClassTypeCapture(Building.class);
        System.out.println(ctt1.f(new Building()));
        System.out.println(ctt1.f(new House()));

        ClassTypeCapture ctt2 = new ClassTypeCapture(House.class);
        System.out.println(ctt2.f(new Building()));
        System.out.println(ctt2.f(new House()));
    }

}

输出

true
true
false
true

你可能感兴趣的:(15.8 擦除的补偿)