这个很奇怪。我有以下代码:
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编译器编译的。)
答案 0 :(得分:8)
问题Why make a method volatile in java?已经涵盖了这个答案。但这里有更多信息。
当重载方法(可能只是超类中的泛型方法)时,该方法被标记为"bridge method"。来自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);
}
答案 1 :(得分:4)
这并不意味着什么。这是反编译器中的一个错误。故事结束。
(该错误可能与类文件格式中使用的某些标志位“重载”这一事实有关,这意味着在类,字段或方法的上下文中有不同的东西。我还模糊地回忆起有一些最近的JVM规范版本中的“新用途”。)
答案 2 :(得分:4)
字段和方法的修饰符掩码类似但不完全相同。反编译器最有可能在这里使用toString
方法
但它没有做的是处理所有位
// 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
它不能处理的是可以表示编译器生成的代码的synthetic
和bridge
的位。
如果volatile
在这里意味着任何事情,那么即使它没有做任何事情,也可能意味着不要删除该方法。
答案 3 :(得分:1)