美文网首页
reflect vs MethodHandles

reflect vs MethodHandles

作者: 全都是泡沫啦 | 来源:发表于2018-11-28 11:37 被阅读0次
    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();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:reflect vs MethodHandles

          本文链接:https://www.haomeiwen.com/subject/hyjaqqtx.html