在运行时更改java类
这是我的问题。假设有两个类,
Class A --> in package PA
Class B --> in package PB
在编译时,我定义了类A和类B。
现在,无论我在编译时在类B中定义了什么,我都想在运行时将其更改为与类A相同。我的意思是当B类在运行时加载时,我想删除所有定义的属性、方法。然后将 A 类中定义的所有内容添加到 B 类中。
因此,B 类就像 A 类的虚拟副本。在运行时,B 类与 A 类相同,只是它们位于不同的包中。
这可能吗?又如何呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为你可以修改加载的类。您可以代理它,从而更改行为,但它不会修改加载的类,并且您应该有能力在正确的位置注入您的实现。
这是使用 setter 有时/通常比在代码中调用 new 更好的原因之一;它将提供注入模拟对象(或代理)而不是运行时实现的能力。
我很高兴这是不可能的(或者不应该对 JVM 进行修改),因为这将是一个巨大的安全漏洞。
您可以通过使用特制的类加载器来实现类似的效果,该类加载器可以识别所请求的类并返回不同的内容。尽管那是一场等待发生的事故。
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.