Java 类可以在运行时向自身添加方法吗? [英] Can a Java class add a method to itself at runtime?
问题描述
一个类是否可以在运行时向自身添加一个方法(比如从 static
块),这样如果有人在这个类上执行反射,他们会看到新方法,即使它没有在编译时定义?
Can a class add a method to itself at runtime (like from a static
block), so that if someone is performing reflection on this class, they'll see the new method, even though it wasn't defined at compile time?
背景:
我使用的框架期望 Action
类被定义为具有 doAction(...)
方法,按照惯例.框架在运行时检查这些类以查看它们的 doAction()
方法中可用的参数类型.例如:doAction(String a, Integer b)
A framework I'm using expects Action
classes to be defined that have a doAction(...)
method, by convention. The framework inspects these classes at runtime to see what type of parameters are available in their doAction()
method. For example: doAction(String a, Integer b)
我希望每个类都能够以编程方式生成具有各种参数的 doAction()
方法,在检查时及时生成.方法体可以为空.
I'd like each class to be able to programatically generate its doAction()
method with various parameters, just-in-time when it is inspected. The body of the method can be empty.
推荐答案
这并不简单.一旦类加载器加载了类,就无法更改加载类的方法.当一个类被请求时,类加载器将加载它并链接它.并且(使用 Java)无法更改链接代码或添加/删除方法.
It's not simple. Once a class is loaded by a classloader, there is no way to change the methods of loaded classes. When a class is requested, a classloader will load it and link it. And there is no way (with Java) to change the linked code or to add/remove methods.
我想到的唯一技巧就是使用类加载器.如果我们删除自定义类加载器,那么该类加载器加载的类也应该被删除或无法访问.我想到的想法是
The only trick that comes to my mind is playing with classloaders. If we delete a custom classloader, then the classes loaded by that classloader should be deleted or inaccessible too. The idea that comes to my mind is to
- 实现一个自定义类加载器
- 使用自定义类加载器加载动态类
- 如果我们有这个类的更新版本,
- 删除自定义类加载器和
- 使用自定义类加载器的新实例加载此类的新版本
我将其留作思考的食物,无法证明这是否会导致解决方案或我们是否存在陷阱.
I leave that as food for thought, can't prove, if this leads to a solution or if we have pitfalls.
作为对这个问题的简单回答:不,我们不能像我们可以通过反射改变字段的内容那样改变一个加载的类.(我们也不能添加或删除字段).
As a simple answer to the question: No, we can't change a loaded class like we can change the content of fields with reflection. (we can't add or remove fields too).
这篇关于Java 类可以在运行时向自身添加方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!