向java.lang.Object添加一个字段 [英] Add a field to java.lang.Object

查看:841
本文介绍了向java.lang.Object添加一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Object 类中添加了一个字段,如下所示:

I added a field to Object class, as in :

class Object {
   ...

   private Object _objInfo;
}

我改变了 java.lang.Object 的源代码并重新编译OpenJDK 6.当VM启动时,我收到以下异常:

I changed java.lang.Object's source code and recompiled OpenJDK 6. I get the following exception when the VM boots:

Error occurred during initialization of VM
    java.lang.IllegalStateException
    at java.lang.Throwable.initCause(Throwable.java:337)
    at java.lang.ExceptionInInitializerError.<init>(ExceptionInInitializerError.java:79)

当我定义自己的Object类并将其添加到bootclasspath时,会出现同样的问题,如in:

The same problem occurs when I define my own Object class and prepended it to bootclasspath, as in:

java -Xbootclasspath/p:<path to my Object class>

谢谢,
Horatiu

Thanks, Horatiu

推荐答案

不要修改对象。不要修改 java.lang 中的任何内容。我不知道它是否在技术上是可行的,但它绝对是一个非常糟糕的主意,并且基本上打破了Java平台( Q Object.equals的合同是什么( ) A :这取决于对JVM的自定义修改使它做什么......) - 你将无法完成任何工作。

Don't modify Object. Don't modify anything in java.lang. I don't know if it's technically possible, but it is definitely an exceptionally bad idea, and basically breaks the Java platform ("Q: What's the contract of Object.equals()? A: It depends what the custom modifications to the JVM make it do...") - you wouldn't be able to get anything done.

想想你正在做什么 - 你将这个类(和可能的行为)添加到每个对象。 ClassLoaders,Strings,Threads,InputStreams,Throwables,XMLGregorianCalendar,一切。这几乎肯定不是你想要的。

Think about what you're doing - you're adding this class (and possible behaviour) to every object. ClassLoaders, Strings, Threads, InputStreams, Throwables, XMLGregorianCalendar, everything. This is almost certainly not what you intended.

相反,另一种方法是将你的修改添加到抽象类 AppnameSuperObject ,并为真正想要将此行为添加到的类扩展此内容。

Instead, an alternative approach would be to add your modifications to an abstract class AppnameSuperObject, and extend this for the classes that you really want to add this behaviour to.

另一方面,如果您真的想为所有对象执行此操作以进行某种日志记录/分析/等工作,请查看使用面向方面的编程在运行时将额外的字段编织到类上

On the other hand, if you really do want to do this for all objects for some kind of logging/profiling/etc kind of work, look at using aspect-oriented programming to weave the extra fields onto the classes at runtime.

这篇关于向java.lang.Object添加一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆