Java泛型总结(四)

Java泛型程序设计中的一些限制和局限:
1)不能用基本类型实例化类型参数
     例如Pair<double>是不可能出现的,原因是类型擦除(见总结第3篇)之后,Pair会含有Object的域,但是Object不能存储double或者int等基本类型的值。

2)运行时类型查询只适用于原始类型
     比如instanceof或者强制转换就涉及到,运行时类型检查,那意思就是说,
     o instanceof Pair<String> 实际就是相当于 o instanceof Pair,String或者T之类的都被忽略。
     Pari<String> pair = (Pair<String>) o; o只要是Pair类型就可以了,String同样被忽略。
     因此,
     Pair<String> sPair = ...;
     Pair<Date> dPair = ...;
     sPair.getClass() == dPair.getClass() 为true,它们都返回的是Pair.class。

3)不能抛出也不能捕获泛型类实例
     泛型类不能扩展异常类Throwable!
     public class MyException<T> extends Exception { /*  */ }  // error
     不能在catch子句中使用类型变量,如下是不允许的:
     public <T extends Throwable> void doWork(Class<T> t) {
          try{
               do something
          }catch(T t){ // ERROR
          
          }
     }

However, it is ok to use type variables in exception specifications. The following 
method is legal:
public static <T extends Throwable> void doWork(T t) throws T // OK

   try
   {
       do work
   }
   catch (Throwable realCause)
   {
      t.initCause(realCause);
      throw t; 
   }
}

4)参数化类型的数组不合法
     简单的说,就是 Pair<String>[] pairs = new Pair<String>[100] 是ERROR的,
     这种情况最好的方法是使用ArrayList<Pair<String>>既安全又有效。

5)不能实例化类型变量,就是不能使用new T(...), new T[...],或者T.class这样的表达式
     例如,下面这样的代码,
     public static <T extends Comparable> T[] test(T[] a){
          Object[] m = new Object[2];
          ...;
          return (T[]) m;
     }
     在执行String[] ss = test("aa", "bb");时就就出现异常,因为它试图讲Object[]赋给String[].
     但是,我们可以通过反射来解决这个问题,就是调用Array.newInstance:
     public static <T extends Comparable> T[] test(T[] a){
          T[] m = (T[]) Array.newInstance(a.getClass().getComponentType(), 2);
           ...;
     }

6)泛型类的静态上下文中类型变量无效(Type Variables Are Not Valid in Static Contexts of Generic Classes)
You cannot reference type variables in static fields or methods. For example, the follow-
ing clever idea won’t work:

  public class Singleton<T>
  {
     public static T getSingleInstance() // ERROR
     {
        if (singleInstance == null) construct new instance of T
        return singleInstance;
     }
     private static T singleInstance; // ERROR
  }

If this could be done, then a program could declare a Singleton<Random> to share a random
number generator and a  Singleton<JFileChooser> to share a file chooser dialog. But it can’t
work. After type erasure there is only one Singleton class, and only one singleInstance field.
For that reason, static fields and methods with type variables are simply outlawed. 

7)最后,要注意擦除后的冲突
例如:
class Calendar implements Comparable<Calendar> { . . . }
class GregorianCalendar extends Calendar implements Comparable<GregorianCalendar>
   { . . . } // ERROR   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值