方法签名中的’volatile’?

这个很奇怪。 我有以下代码:

class A { protected A clone() throws CloneNotSupportedException { return (A) super.clone(); } } 

当我通过’showmycode.com’解码其字节码时,它向我展示了以下代码:

 class A { A() { } protected A clone() throws clonenotsupportedexception { return (A)super.clone(); } protected volatile object clone() throws clonenotsupportedexception { return clone(); } } 

在第二个’clone’方法中,方法返回类型是volatile的意思是什么? (此代码是通过Eclipse的默认JDK 1.6编译器编译的)。

字段和方法的修饰符掩码类似但不完全相同。 反编译器最有可能在这里使用toString方法

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/reflect/Modifier.java

但它没有做的是处理所有的比特

 // Bits not (yet) exposed in the public API either because they // have different meanings for fields and methods and there is no // way to distinguish between the two in this class, or because // they are not Java programming language keywords 

它不能处理的是可以表示编译器生成的代码的syntheticbridge的位。

如果volatile在这里意味着什么,它可能意味着即使它没有做任何事情也不要删除该方法。

这个答案已经在为什么在java中使方法易变? 但这里有更多信息。

当重载方法(可能只是超类中的generics方法)时,该方法被标记为“桥接方法” 。 来自java.lang.reflect.Modifier

 static final int BRIDGE = 0x00000040; 

不幸的是,这与用于将字段标记为volatile位相同:

 public static final int VOLATILE = 0x00000040; 

如果在该方法上打印修改器,您将看到如下内容:

 public volatile 

这是Modifiers.toString(int)方法中的限制,该方法不知道它是字段还是方法。

 public static String toString(int mod) { StringBuffer sb = new StringBuffer(); ... if ((mod & VOLATILE) != 0) sb.append("volatile "); // no mention of BRIDGE here ... return sb.toString().substring(0, len-1); } 

它没有任何意义。 这是反编译器中的一个错误。 故事结局。

(该错误可能与类文件格式中使用的某些标志位“重载”这一事实有关,这意味着类,字段或方法的上下文中的不同内容。我还模糊地回忆起有一些“新用途” “在最近的JVM规范版本中。)

这是你的反编译器中的一个错误。

volatile只是字段的有效修饰符。

我建议你阅读这篇论文。