如何识别Java字节码中的override方法?
我现在专注于一个需要深入了解 Java 字节代码的项目。
在 bcel 的帮助下,我现在可以完成大部分工作。我现在不清楚的一点是如何识别子类方法覆盖其基本代码? .class 文件中是否记录了与指示此重写关系的方法关联的任何属性,或者我应该返回到其基类可以比较方法签名?
任何提示将不胜感激。
I'm now focusing on a project requiring insight of Java byte code.
With the help of bcel, I can now complete most of the work. One point that I'm now not clear is how to identify a sub-class method override its base code? Is there any attribute recorded in the .class
file associated with a method indicating this overriding relationship or should I go backwards to its base class can compare method signatures?
Any hints will be highly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要查找层次结构链 - 字节代码中没有任何内容表明它是重写的方法,因为不需要这样做。
You need to look up the hierarchy chain--there's nothing in the byte code that indicates it's an overridden method, because there doesn't need to be.
如果您不能依赖
@Override
属性,那么根据 规范 没有其他方法可以通过仅查看类来了解。我认为你需要看看超类。If you can't rely on the
@Override
attribute then it seems that according to the spec there is no other way to know by looking just at the class. I think you need to look at the superclasses.不幸的是,您无法从字节码中看出这一点。 @Override 注释只是一种建议性注释 - 它不是强制性的。
JVM 定义了 5 种调用方法的方式。它们是invokevirtual、invokeinterface、invokespecial、invokestatic 和新的invokedynamic。
重点关注 invokevirtual - 这是最常见的调度形式,也是您在这里讨论的情况所使用的一种形式。
invokevirtual 的工作方式是在运行时查看您正在分派的对象的类。如果它找到我们所追求的方法的实现,那么它就会调用它。如果不是,那么它会查看该对象类的超类并再次尝试,依此类推。
因此,如果不查看父类的字节码,就无法从字节码可靠地判断给定方法是否被重写。
Unfortunately, you can't tell that from the bytecode. The annotation @Override is only an advisory one - it's not mandatory.
The JVM defines 5 ways of invoking a method. They are invokevirtual, invokeinterface, invokespecial, invokestatic and the new invokedynamic.
Focus on invokevirtual - it's the most common form of dispatch and is the one used for the case you're talking about here.
The way that invokevirtual works is that at runtime it looks at the class of the object you're dispatching on. If it finds an implementation of the method we're after, then it calls it. If not, then it looks at the superclass of the object's class and tries again, and so on.
So there is no way from the bytecode to reliably tell whether a given method is overridden, without looking at the bytecode for the parent class.
编译后生成字节码。因此,它仅假设基于引用变量调用方法,因为对象尚未创建。
The byte code is generated after the compilation. So, it only assumes the method to be called based upon the reference variable, as the object is not yet created.
您可以反编译它并将代码作为项目加载到您选择的 IDE 中。通常,您可以轻松地从继承类跳转到重写的方法。
You could decompile it and load the code as a project in the IDE of you choice. Normally you can easily jump to overridden methods from the inheriting class.