简体   繁体   English

如何使java.lang.Object.clone公开?

[英]How to make java.lang.Object.clone public?

具体来说:如何修改java.lang.Object.clone以便在字节码调用JVM时不会发出尖叫声?

You cannot modify java.lang.Object.clone() . 您不能修改java.lang.Object.clone() You can override clone() to make it a public method in any class you define, although it is fairly useless to do so unless the class (or some class in its hierarchy) is declared to implement the Cloneable interface. 您可以重写clone()使其成为您定义的任何类中的公共方法,尽管这样做是没有用的,除非声明该类(或其层次结构中的某个类)以实现Cloneable接口。

public class MyClass implements Cloneable {
    public Object clone() {
        return super.clone();
    }
}

The other usual approach to copying is to define a copy constructor: 另一种常用的复制方法是定义一个复制构造函数:

public class MyClass {
    public MyClass() {
        // standard default constructor
    }

    public MyClass(MyClass other) {
        // copy constructor -- initialize from values in other
    }
}

Peter Lawrey's comment gave the idea of editing rt.jar . Peter Lawrey的评论提出了编辑rt.jar的想法。 This works. 这可行。 It is also utterly harmless. 它也是完全无害的。

(changed access modifier code 0x0104 to 0x0101 at the right place in rt.jar/java/lang/Object.class ) (将访问修饰符代码0x0104 0x0101rt.jar/java/lang/Object.class正确位置的0x0101

Similarly, one can construct an rtplus.jar containing just the modified class file and use -Xbootclasspath/p:rtplus.jar to have java use that version instead. 同样,可以构造一个rtplus.jar包含修改后的类文件的rtplus.jar ,然后使用-Xbootclasspath/p:rtplus.jar来让java使用该版本。 (and yes, EJP, we can't distribute that rtplus.jar but it's quite easy to generate programmatically) (是的,EJP,我们无法分发该rtplus.jar但以编程方式生成它非常容易)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM