多态调用:从字节码解析目标方法
给出Java字节码和ASM字节码分析框架,
发生多态调用时如何解析目标方法?
例如:
class ClassA {
public void foo() {…}
}
class ClassB extends ClassA {
public void foo() {…}
}
…
ClassA inst = new ClassB();
inst.foo();
为后一行生成以下字节码:
…
INVOKEVIRTUAL ClassA.foo()V
…
该结构针对父方法。
但实际的方法是ClassB.foo()
。
如何解析将被调用的“真实”方法?
Given Java bytecode and ASM bytecode analysis framework,
how can I resolve a target method when polymorphic call occurs?
For instance:
class ClassA {
public void foo() {…}
}
class ClassB extends ClassA {
public void foo() {…}
}
…
ClassA inst = new ClassB();
inst.foo();
The following bytecode is generated for the latter line:
…
INVOKEVIRTUAL ClassA.foo()V
…
This instructure targets a parent method.
But the actual method is ClassB.foo()
.
How can I resolve the "real" method that will be called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说:你不能。这是无法确定的。但也有特殊情况可以分析。一种方法是应用points-to-analysis。这通常是整个程序分析。在存在字节码重写和/或反射的情况下,会出现其他问题。
所以基本上你必须决定你愿意花费多少努力。您有以下选择:
您首先想实现什么目标?
In general: you can't. It's undecidable. But there are special case which can be analyzed. One way to do it is to apply a points-to-analysis. Which usually is a whole program analysis. In the presence of bytecode rewriting and or reflection additional problems occur.
So basically you have to decide how much effort you are willing to spend. You have the following options:
What do you want to achieve in the first place?
我对ASM一无所知,但我怀疑你也不会。字节码在运行时解释。因此,所调用的方法将在运行时调用。因此,根据应用程序的状态,可能会在
ClassB
和ClassC
上调用foo()
。免责声明如果 ASM 允许询问正在运行的 JVM(如调试器),那么您应该能够这样做!
I don't know anything about ASM, but I suspect that you can't. Bytecode is interpreted at runtime. As such, the method that's invoked will be invoked at runtime. So
foo()
might be invoked onClassB
and onClassC
depending on the state of the application.Disclaimer if ASM allows interrogation of a running JVM (like a debugger) then you should be able to!