In the application, we use Java to reflect the scene is not many, but occasionally also used. Frames are more reflective, such as MyBatis, Spring, and so on.
In JDK7, a new Java.lang.invoke.MethodHandle was added, called "Modern reflection."
In fact, both reflection and java.lang.invoke.MethodHandle are indirect methods, but java.lang.invoke.MethodHandle is more concise than reflection, and the reflection function will write a lot of redundant code.
An explanation given by the official API:
A method handle is a typed, directly executable reference to an underlying method, constructor, field, or similar Low-leve L operation, with optional transformations of arguments or return values.
Actually see this, I think of the University of Learning VC (6) in the MFC framework is full of various Handle, in fact, similar to the pointer, but more secure than the pointer to a thing.
In the following example, we use methodhandle to call the ToString () method:
public class Methodhandle {@Overridepublic String toString () {return super.tostring () + "==methodhandle";} public static void Main (string[] args) throws Throwable {Methodhandle handle = new Methodhandle (); Methodtype Methodtype = Methodtype.methodtype (String.class); Lookup lookup = Methodhandles.lookup (); Java.lang.invoke.MethodHandle methodhandle = Lookup.findvirtual ( Methodhandle.class, "toString", Methodtype); String toString = (string) methodhandle.invokeexact (handle); System.out.println (toString);//[email protected]==methodhandle//or like This:java.lang.invoke.MethodHandle MethodHandle2 = Methodhandle.bindto (handle); String toString2 = (string) methodhandle2.invokewitharguments (); System.out.println (toString2);//[email protected]==methodhandle//get the different representations of the current class, the last best. Generally we use SLF4J in static context to get logger. System.out.println (Methodhandle.class); System.out.println (Handle.getclass ()); System.out.println (Methodhandles.lookup (). Lookupclass ()); Like GetClass ()}}
Look, actually.
Methodtype
Represents a function signature, which is a class of functions that conform to the signature of the function. We can use
Lookup
To find this function under a specific class.
The last few lines of code are the kinds of different methods that we often use to get the current class with logs such as SLF4J.
Copyright NOTICE: This article for Bo Master original article, without BO Master permission cannot reprint [http://blog.csdn.net/doctor_who2004].
The Java.lang.invoke.MethodHandle of Jdk7