简体   繁体   中英

change the java class at runtime

Here is my question. Let's say there are two classes,

Class A --> in package PA
Class B --> in package PB

At compiling time, I define Class A and Class B.

Now, no matter what I have defined in Class B at compiling time, I want to change it to be the same as Class A at runtime. I mean when Class B is being loaded at runtime, I want to delete all the defined attributes, methods. etc. Then add everything defined in Class A to Class B.

So Class B is like a dummy copy of Class A. And at runtime, Class B is the same as Class A except that they in different package.

Is this possible? and how?

I don't think you can modify a loaded class. You can proxy it, and thus change behaviour, but it would not modify the loaded class and you should have the abitiy to inject your implementation at the correct position.

This is one of the reasons having setters is sometimes/often better than calling new in your code; it would give the ability to inject a mock object (or proxy) in stead of the runtime implementation.

I for one am very glad it is not possible (or should not be without modifications to the JVM) as it would be a tremendous security breach.

You could possibly achieve a similar effect by using a specially crafted classloader which recognizes the requested class and returns something different. Though that is an accident waiting to happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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