用反射改变java类的超类
是否可以通过反射在运行时更改类对象的继承层次结构?
我的情况是:
SuperClass
MiddleClass 扩展 SuperClass
BottomClass 扩展 SuperClass
我想在运行时使用反射来更改 BottomClass 以扩展 MiddleClass。这可能吗?
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 Java 最接近的方法是 仪器仪表。基本上,您编写一些 Java 类,这些类被赋予定义类的一系列字节,处理字节代码,并返回修改后的类文件字节数组。然后,您将这些类打包到 JAR 文件中,并通过命令行或通过将属性放入检测 JAR 文件的清单文件中来告诉 JVM 使用它们。
当然,如果您这样做,您需要使用一些字节码操作库,例如 ASM。
编辑:如果您感兴趣的类实现了接口,您可能需要查看动态代理类 通过 java.lang.reflect.Proxy。这样做的缺点是,您没有编写的执行
new ClassOfInterest()
的代码片段不受影响,但优点是: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:SecurityManager
issues.不,通过反射是不可能的,因为反射用于分析现有代码,而不是更改它。
No, it's not possible through reflection becuase reflection is used to analyze the existing code, not to change it.
继承是静态的,因此不能在运行时更改。
但是,您可以将
SuperClass
设为接口或使用委托而不是继承。Inheritance is static, so it cannot be changed at runtime.
However you could make
SuperClass
an interface or use delegation instead of inheritance.这是不可能的。例如,如果您已经有一个 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...