Java中关于泛型擦除的概括
发布时间:2021-11-24 13:39:19 所属栏目:教程 来源:互联网
导读:Java由于擦除,在使用泛型的时候一些操作成了程序存在异常的可能 ,这个类中展示了一些容易出现的问题,下面的小例子做了一个简单的总结 class ErasedT { public static void f(Object arg) { // if (arg instanceof T) { // } // Error // T var = new T(); //
|
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"; } } ![]() (编辑:葫芦岛站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐


