静态方法如何在 Java 中实际运行?我们通常使用类名来调用它们,并不为它们创建任何对象,但这些是真正可以“运行”的对象,而不是方法!
最佳答案
对于静态方法,一个特殊的关键字可用 并添加为字节码 的一部分。它称为 invokestatic
。
来自 Oracle docs :
静态调用
Operation
Invoke a class (static) method
Description :
The unsigned indexbyte1 and indexbyte2 are used to construct an index into the run-time constant pool of the current class (§2.6), where the value of the index is (indexbyte1 << 8) | indexbyte2. The run-time constant pool item at that index must be a symbolic reference to a method (§5.1), which gives the name and descriptor (§4.3.3) of the method as well as a symbolic reference to the class in which the method is to be found. The named method is resolved (§5.4.3.3). The resolved method must not be an instance initialization method (§2.9) or the class or interface initialization method (§2.9). It must be static, and therefore cannot be abstract.
On successful resolution of the method, the class that declared the resolved method is initialized (§5.5) if that class has not already been initialized.
The operand stack must contain nargs argument values, where the number, type, and order of the values must be consistent with the descriptor of the resolved method.
示例代码:
public class Example {
static void myStaticMethod() {
System.out.println("Hello");
}
public static void main(String[] args) {
myStaticMethod();
}
字节码:
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=0, locals=1, args_size=1
0: invokestatic #31 // Method myStaticMethod:()V
3: return
LineNumberTable:
line 8: 0
line 9: 3
LocalVariableTable:
Start Length Slot Name Signature
0 4 0 args [Ljava/lang/String;
类的运行时常量池:
...
#31 = Methodref #1.#32 // Example.myStaticMethod:()V
...
关于java - 静态方法如何运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30232853/