`
laolinshi
  • 浏览: 41003 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

JAVA方法中Bridge修饰符

 
阅读更多

    前段时间研究spring中的autowireByType实现原理时,看到了一个方法修饰符bridge,由于以前没有见过这个修饰符,不知道它表示的具体含义,后面的代码也就看不明白了,原理研究也就搁在那里了,没什么进展。恰好这几天在阅读《JAVA泛型与集合》这本书时,看到了书中有对这个修饰符的讲解,才稍微有点眉目。原来这个修饰符不是给程序员使用的,而是编译器为了实现泛型而自动产生的。书中描述如下:

       As we mentioned earlier, generics are implemented by erasure: when you write code
with generics, it compiles in almost exactly the same way as the code you would have
written without generics. In the case of a parameterized interface such as Compara
ble<T>, this may cause additional methods to be inserted by the compiler; these additional
methods are called bridges.

  

     下面举个列子解释一下这段话的意思。

     

     在JDK1.5之前,是不存在泛型的,对象需要比较时需要实现Comparable接口,此时接口如下:

interface Comparable {
      public int compareTo(Object o);
}

       可以看出接口中定义了一个接受参数类型为Object的比较方法,而JDK中的Integer对象实现了这个接口,简化的代码列出如下:

 

class Integer implements Comparable {
      private final int value;

      public Integer(int value) { this.value = value; }

      public int compareTo(Integer i) {
             return (value < i.value) ? -1 : (value == i.value) ? 0 : 1;
      }

      public int compareTo(Object o) {
            return compareTo((Integer)o);
      }

}

       类中的存在两个比较方法,一个参数类型为Object,是Comparable 接口中定义方法的具体实现,此外,还定义了一个接受Integer参数类型的比较方法,是为了方便前者方法实现而添加的。当一个对象需要和另一个对象比较时,就需要把后者当做Object对象参入前者的compareTo方法中,这样容易发生意外情况,就是不是Integer的实例,转型的就抛异常了,而这个通常都不在编译期避免。

 

     在JDK1.5之后可以使用泛型了,比较对象的Comparable接口变成下面的样子了:

interface Comparable<T> {
     public int compareTo(T o);
}

   可以看出接口没有定义接受Object类型的方法了,而是定义一个接受T类型的方法,这个T类型就代表具体的类类型。

   此时,实现了比较方法的Integer类如下:

class Integer implements Comparable<Integer> {
      private final int value;
      
      public Integer(int value) { this.value = value; }
      
      public int compareTo(Integer i) {
            return (value < i.value) ? -1 : (value == i.value) ? 0 : 1;
      }

}

    类中不存在接受Object类型的比较方法,只存在一个接受Integer类型的方法,就可以在编译期避免传入不是Integer的实例时而引起的异常。此时你用反射查看Integer类的方法时,可以看到一个带有Bridge修饰符接受参数为Object的方法,查看代码如下:

for (Method m : Integer.class.getMethods())
     if (m.getName().equals("compareTo"))
           System.out.println(m.toGenericString());

 执行这段代码,打印结果如下:

public int Integer.compareTo(Integer)
public bridge int Integer.compareTo(java.lang.Object)

 

  

   

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics