How to identify override method in Java byte code?

2019-02-17 05:00发布

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.

5条回答
Viruses.
2楼-- · 2019-02-17 05:35

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.

查看更多
叼着烟拽天下
3楼-- · 2019-02-17 05:42

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.

查看更多
成全新的幸福
4楼-- · 2019-02-17 05:53

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.

查看更多
Ridiculous、
5楼-- · 2019-02-17 05:53

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.

查看更多
Explosion°爆炸
6楼-- · 2019-02-17 05:58

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.

查看更多
登录 后发表回答