用反射改变java类的超类

发布于 2024-12-14 01:22:19 字数 204 浏览 2 评论 0 原文

是否可以通过反射在运行时更改类对象的继承层次结构?

我的情况是:

SuperClass

MiddleClass 扩展 SuperClass

BottomClass 扩展 SuperClass

我想在运行时使用反射来更改 BottomClass 以扩展 MiddleClass。这可能吗?

谢谢

Is it possible to change the inheritance hierarchy of class objects at runtime with reflection?

My situation is I have:

SuperClass

MiddleClass extends SuperClass

BottomClass extends SuperClass

I would like to use reflection at runtime to change BottomClass to extend MiddleClass. Is this possible?

THanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

疯到世界奔溃 2024-12-21 01:22:19

使用 Java 最接近的方法是 仪器仪表。基本上,您编写一些 Java 类,这些类被赋予定义类的一系列字节,处理字节代码,并返回修改后的类文件字节数组。然后,您将这些类打包到 JAR 文件中,并通过命令行或通过将属性放入检测 JAR 文件的清单文件中来告诉 JVM 使用它们。

当然,如果您这样做,您需要使用一些字节码操作库,例如 ASM

编辑:如果您感兴趣的类实现了接口,您可能需要查看动态代理类 通过 java.lang.reflect.Proxy。这样做的缺点是,您没有编写的执行 new ClassOfInterest() 的代码片段不受影响,但优点是:

  1. 比修改类的字节码容易得多。
  2. 您可以动态地选择使代理的不同实例表现得就像它们具有不同的超类一样。
  3. 您不必担心任何 SecurityManager 问题。

The closest you can get to this with Java is instrumentation. Basically you write some Java classes which are given the series of bytes which define a class, muck around with the byte code, and return the modified class file byte array. You then package these classes up in a JAR file and tell the JVM to use them, either on the command line or by putting an attribute into the manifest file of the instrumentation JAR file.

Of course, if you do this, you'd want to use some byte code manipulation library like ASM.

EDIT: If the class you're interested in implements interfaces you might want to take a look at dynamic proxy classes via java.lang.reflect.Proxy. This has the disadvantage that pieces of code which you didn't write which do new ClassOfInterest() are unaffected, but has the advantages of:

  1. Being a lot easier than modifying the byte code of classes.
  2. You can dynamically choose to make different instances of the proxies act like they have different superclassess.
  3. You don't have to worry about any SecurityManager issues.
叹沉浮 2024-12-21 01:22:19

不,通过反射是不可能的,因为反射用于分析现有代码,而不是更改它。

No, it's not possible through reflection becuase reflection is used to analyze the existing code, not to change it.

还如梦归 2024-12-21 01:22:19

继承是静态的,因此不能在运行时更改。

但是,您可以将 SuperClass 设为接口或使用委托而不是继承。

Inheritance is static, so it cannot be changed at runtime.

However you could make SuperClass an interface or use delegation instead of inheritance.

几度春秋 2024-12-21 01:22:19

这是不可能的。例如,如果您已经有一个 BottomClass 对象,并且您试图更改超类,那么该对象会发生什么?这是不可能的...

it is not possible.For example if you already have an object of BottomClass and you are trying to change super class, what will happen to that object? it's impossible...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文