java中关于泛型擦除的小结

java由于擦除,在使用泛型的时候一些操作成了程序存在异常的可能 ,这个类中展示了一些容易出现的问题,下面的小例子做了一个简单的总结

class Erased<T> {

    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]; // Unchecked warning
	}
}

下面的程序算是对擦除特性的一个弥补

/*casionally you can program around these issues, but sometimes you must compensate for erasure by introducing a type
* tag . This means you explicitly pass in the Class object for your type so that you can use it in type expressions.
* For example, the attempt to use instanceof in the previous program fails because the type information has been
* erased. If you introduce a type tag, a dynamic islnstance( ) can be used instead:
*/

public class CompensatErasure<T> {
    public static void main(String[] args) {
        CompensatErasure<Building> ctt1 = new CompensatErasure<Building>(Building.class);
        ctt1.f(new Building());
        ctt1.f(new House());
        CompensatErasure<House> ctt2 = new CompensatErasure<House>(House.class);
        ctt2.f(new Building());
        ctt2.f(new House());
    }

    private Class<T> type;

    public CompensatErasure(Class<T> type) {
        this.type = type;
    }

    /**
     * @return the type
     */
    public Class<T> getType() {
        return type;
    }

    /**
     * @param type
     *            the type to set
     */
    public void setType(Class<T> type) {
        this.type = type;
    }

    @SuppressWarnings("unchecked")
    public void f(Object obj) {
        // Compensate instance of
        if (type.isInstance(obj)) {
            System.out.println(obj + " is instance of " + type.getSimpleName());
        } else {
            System.out.println(obj + " doesn't  instance of " + type.getSimpleName());
        }
        try {
            // Compensate new T();
            System.out.println(type.newInstance());
            // compensate new T[]{};
            Class<T>[] types = new Class[1];
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}

class Building {
	@Override
	public String toString(){
		return "Building";
	}
}

class House extends Building {
	@Override
	public String toString(){
		return "House";
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值