简体   繁体   English

如何识别Java字节码中的覆盖方法?

[英]How to identify override method in Java byte code?

I'm now focusing on a project requiring insight of Java byte code. 我现在专注于需要深入了解Java字节代码的项目。

With the help of bcel , I can now complete most of the work. bcel的帮助下,我现在可以完成大部分工作。 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? .class文件中是否记录了与指示此重写关系的方法相关联的属性,或者我应该向后回到其基类可以比较方法签名?

Any hints will be highly appreciated. 任何提示将受到高度赞赏。

您需要查找层次结构链 - 字节代码中没有任何内容表明它是一个被重写的方法,因为不需要。

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. 如果您不能依赖@Override属性,那么根据规范似乎没有其他方法可以通过查看类来了解。 I think you need to look at the superclasses. 我想你需要看一下超类。

Unfortunately, you can't tell that from the bytecode. 不幸的是,你无法从字节码中分辨出来。 The annotation @Override is only an advisory one - it's not mandatory. 注释@Override只是一个建议 - 它不是强制性的。

The JVM defines 5 ways of invoking a method. JVM定义了5种调用方法的方法。 They are invokevirtual, invokeinterface, invokespecial, invokestatic and the new invokedynamic. 它们是invokevirtual,invokeinterface,invokespecial,invokestatic和新的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. 专注于invokevirtual - 这是最常见的调度形式,是你在这里谈论的案例。

The way that invokevirtual works is that at runtime it looks at the class of the object you're dispatching on. invokevirtual的工作方式是在运行时它查看您要调度的对象的类。 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. 因此,它仅假定基于引用变量调用方法,因为尚未创建对象。

You could decompile it and load the code as a project in the IDE of you choice. 您可以对其进行反编译,并将代码作为项目加载到您选择的IDE中。 Normally you can easily jump to overridden methods from the inheriting class. 通常,您可以轻松地从继承类跳转到重写的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM