参考文档:https://www.javacodegeeks.com/2011/03/glimpse-at-java-7-methodhandle-and-its.html
Due to Java’s Reflection API we have been able to inspect and alter program execution at runtime. In particular, we can observe interfaces/classes/methods and fields at runtime without knowing their names at compile time.
JDK 7 introduces a new player to this dynamic/runtime inspection, the method handle (i.e. a subclass of the abstract class java.dyn.MethodHandle). Method handles gives us unrestricted capabilities for calling non-public methods, e.g. it can be formed on a non-public method by a class that can access it. Compared to using the Reflection API, access checking is performed when the method handle is created as opposed to every time the method is called.
MethodHandle和反射一样也能够实现在运行期间访问私有方法,且更加高效。可以看成是:持有某个具体方法的指针,然后就能直接调用该句柄所引用的底层方法。与使用Reflection API相比,在创建方法句柄时(而不是在每次调用该方法时)执行访问检查。
例子代码:
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class MethodAccessExampleWithArgs{
private final int i;
public MethodAccessExampleWithArgs(int i_) {
i = i_;
}
private void bar(int j, String msg) {
System.out.println("Private Method \'bar\' successfully accessed : "
+ i + ", " + j + " : " + msg + "!");
}
// Using Reflection,使用反射
public static Method makeMethod() {
Method