Java中关于泛型擦除的小结
java由于擦除,在使用泛型的时候一些操作成了程序存在异常的可能 ,这个类中展示了一些容易出现的问题,下面的小例子做了一个简单的总结
- class Erased<T> {
-
- public static void f(Object arg) {
-
-
-
-
-
- }
- }
|
下面的程序算是对擦除特性的一个弥补
-
-
-
-
-
-
- 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;
- }
-
-
-
-
- public Class<T> getType() {
- return type;
- }
-
-
-
-
-
- public void setType(Class<T> type) {
- this.type = type;
- }
-
- @SuppressWarnings("unchecked")
- public void f(Object obj) {
-
- 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 {
-
- System.out.println(type.newInstance());
-
- 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";
- }
- }
|
评论暂时关闭