A method handle is a typed, directly executable reference to an underlying method, constructor, field, or similar low-level operation, with optional transformations of arguments or return values.
public MethodHandle findVirtual(Class<?> refc, String name, MethodType type)
invokestatic
静态方法查找
public MethodHandle findStatic(Class<?> refc, String name, MethodType type)
查找构造函数
public MethodHandle findConstructor(Class<?> refc, MethodType type)
查找非私有字段
/**
* Produces a method handle giving read access to a non-static field.
* The type of the method handle will have a return type of the field's
* value type.
* The method handle's single argument will be the instance containing
* the field.
*/
public MethodHandle findGetter(Class<?> refc, String name, Class<?> type)
/**
* Produces a method handle giving write access to a non-static field.
* The type of the method handle will have a void return type.
* The method handle will take two arguments, the instance containing
* the field, and the value to be stored.
*/
public MethodHandle findSetter(Class<?> refc, String name, Class<?> type)
MethodHandle
使用invoke家族来调用
invoke、invokeWithArguments、invokeExact
MethodType
Lookup需要方法的签名才能找到方法句柄
public static MethodType methodType(Class<?> rtype, Class<?> ptype0, Class<?>... ptypes)
rtype为返回值类型,ptypes为参数类型
QuickStart
class Horse {
public void race() {
System.out.println("Horse.race()");
}
}
class Deer {
public void race() {
System.out.println("Deer.race()");
}
}
class Cobra {
public void race() {
System.out.println("How do you turn this on?");
}
}