Java Dynamic Language Methodhandle (1)

Source: Internet
Author: User

package Vmrun;import Java.lang.invoke.methodhandle;import Java.lang.invoke.methodhandles;import Java.lang.invoke.methodhandles.lookup;import Java.lang.invoke.MethodType; public class Methodhandletest {static class ClassA {public void println (String s) {System.out.println ("ClassA:" +s);}} public static void Main (String [] args) throws Throwable{object Object = System.currenttimemillis ()%2==0? System.out:new ClassA ();//Whether object is for that implementation class, the following can be called correctly to the Println method Getprintlnmh (object). Invokeexact ("LISJ"); private static Methodhandle GETPRINTLNMH (Object receiver) throws throwable{/** * Methodtype means "method type", which contains the return value of the method ( The first parameter) and the specific parameters (the second and subsequent parameters) * Here refer to the method in ClassA */methodtype mt = Methodtype.methodtype (Void.class, string.class);/** * Lookup: Finds a method name in the specified class that conforms to the given method name, has a methods type, and conforms to the calling permission. * This call is a virtual method, the first parameter of the method is implicit, representing the receiver of this method, that is, the object this point, which was previously placed in the parameter list * passed, now provides the BindTo method */return Methodhandles.lookup (). Findvirtual (Receiver.getclass (), "println", MT). BindTo (receiver);}} 

The difference between Methodhandle and reflection:

1. Essentially two are calls in the simulation method, but reflection is a call to emulate the Java code hierarchy, and Methodhandle is the byte-code level of the simulation, the example above is the invokevirtual instruction of the simulation.

The 2.Reflection is heavyweight, while the Methodhandle is lightweight.

Most importantly, Reflection is only for Java services, while Methodhandle can serve all languages running on Java virtual machines.

Java Dynamic Language Methodhandle (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.