Java类可以在运行时向自己添加方法吗? [英] Can a Java class add a method to itself at runtime?

查看:177
本文介绍了Java类可以在运行时向自己添加方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个类可以在运行时向自己添加一个方法(比如从 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?

背景:

Background:

我正在使用的框架需要 Action 要定义的具有 doAction(...)的类按惯例,方法。框架在运行时检查这些类,以查看其 doAction()方法中可用的参数类型。例如:doAction(字符串 a,整数 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


  1. 实现一个自定义类加载器

  2. 加载具有该自定义类加载器的动态

  3. 如果我们有此类的更新版本,

  4. 删除自定义类加载器和

  5. 使用自定义类加载器的新实例加载此类的新版本

  1. implement one custom classloader
  2. load the dynamic class with that custom classloader
  3. if we have an updated version of this class,
  4. remove the custom classloader and
  5. load the new version of this class with a new instance of the custom classloader

我把它留作思考的食物,无法证明,如果这导致解决方案或我们有陷阱。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆