import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
/**
* @author paul
* @description
* @date 2018/11/27
*/
public class RunMethod {
public static void reflection() throws Exception {
String methodName = "substring";
Method method = String.class.getDeclaredMethod(methodName, new Class[]{int.class, int.class});
String str = (String) method.invoke("Hello World", new Object[]{1, 3});
System.out.println(str);
}
public static void invokeExact() throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
//(II)Ljava/lang/String;
MethodType type = MethodType.methodType(String.class, int.class, int.class);
MethodHandle mh = lookup.findVirtual(String.class, "substring", type);
String o = (String) mh.invokeExact("Hello World", 1, 3);
//这里的(String必须填写,否则找不到对应的方法)
System.out.println(o);
}
public static void main(String[] args) throws Throwable {
reflection();
invokeExact();
}
}
网友评论