What are CONSTANT_MethodHandle, CONSTANT_MethodType, and CONSTANT_InvokeDynamic?

巧了我就是萌 提交于 2020-05-11 21:17:51

问题


I was looking into how the Java bytecode worked, and I started on Wikipedia. On the page focusing on the .class file, it mentions 11 constant types that appear in the Constant Pool. However, in The Java Virtual Machine Specifications (JVMS) it mentions 3 more:

  • CONSTANT_MethodHandle
  • CONSTANT_MethodType
  • CONSTANT_InvokeDynamic

The 11 mentioned on the Wikipedia page seem fairly self-explanatory, and I understand their purpose and use. However, I'm confused by the 3 extra described in the JVMS. What are they, and for what are they used?


回答1:


MethodHandle is basically a "handle" to an executable operation. It can be a method call or even a variable assignment. MethodType is the calling signature used to call the MethodHandle. In other words, it describes the parameters and return value. A MethodHandle may be able to process being called with different type signatures.

To play around with there, look at java.lang.invoke.MethodHandle and java.lang.invoke.MethodType. These were introduced in Java 7. When bytecode uses LDC to load a MethodHandle_info or MethodType_info constant onto the stack, the JVM creates a MethodHandle or MethodType class instance, respectively.

The invokedynamic bytecode instruction will invoke a MethodHandle. The bootstrap method will be used on the first invocation to determine what MethodHandle it will call. This creates an invoke instruction that can change its call target at runtime. This allows for dynamic code that doesn't need to recompile when certain aspects of its target code change. This is used in Java 8 to provide support for lambda expressions.




回答2:


See the The Java® Virtual Machine Specification Chapter 4. The class File Format :

The CONSTANT_MethodHandle_info structure is used to represent a method handle:

CONSTANT_MethodHandle_info {
    u1 tag;
    u1 reference_kind;
    u2 reference_index;
}

The CONSTANT_MethodType_info structure is used to represent a method type:

CONSTANT_MethodType_info {
    u1 tag;
    u2 descriptor_index;
}

The CONSTANT_InvokeDynamic_info structure is used by an invokedynamic instruction (§invokedynamic) to specify a bootstrap method, the dynamic invocation name, the argument and return types of the call, and optionally, a sequence of additional constants called static arguments to the bootstrap method.

CONSTANT_InvokeDynamic_info {
    u1 tag;
    u2 bootstrap_method_attr_index;
    u2 name_and_type_index;
}

See also Method handles and invokedynamic and Class MethodHandle for more information



来源:https://stackoverflow.com/questions/25088414/what-are-constant-methodhandle-constant-methodtype-and-constant-invokedynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!