java 添加字段,向java.lang.Object添加一个字段

尝试修改java.lang.Object类并重新编译OpenJDK6导致虚拟机启动时出现异常。问题表现为初始化VM时抛出IllegalStateException。解决方案是避免修改标准库,特别是Object类,因为这会破坏Java平台的稳定性。建议使用抽象类来添加额外行为,或者考虑使用面向切面编程在运行时动态织入字段。
摘要由CSDN通过智能技术生成

I added a field to Object class, as in :

class Object {

...

private Object _objInfo;

}

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.(ExceptionInInitializerError.java:79)

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

java -Xbootclasspath/p:

Thanks,

Horatiu

解决方案

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.

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值