简体   繁体   English

在运行时更改 java class

[英]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.在编译时,我定义了 Class A 和 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.现在,无论我在编译时在 Class B 中定义了什么,我都想在运行时将其更改为与 Class A 相同。 I mean when Class B is being loaded at runtime, I want to delete all the defined attributes, methods.我的意思是当 Class B 在运行时加载时,我想删除所有定义的属性、方法。 etc. Then add everything defined in Class A to Class B.等然后将 Class A 中定义的所有内容添加到 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. 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.我认为您不能修改已加载的 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.您可以代理它,从而改变行为,但它不会修改加载的 class 并且您应该有能力将您的实现注入正确的 position。

This is one of the reasons having setters is sometimes/often better than calling new in your code;这是使用 setter 有时/通常比在代码中调用new更好的原因之一; it would give the ability to inject a mock object (or proxy) in stead of the runtime implementation.它将提供注入模拟 object (或代理)而不是运行时实现的能力。

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.我很高兴这是不可能的(或者不应该对 JVM 进行修改),因为这将是一个巨大的安全漏洞。

You could possibly achieve a similar effect by using a specially crafted classloader which recognizes the requested class and returns something different.您可以通过使用特制的类加载器来实现类似的效果,该类加载器识别请求的 class 并返回不同的内容。 Though that is an accident waiting to happen.虽然这是一场等待发生的意外。

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

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