首页 > 其他分享 >Spring 高级-jdk反射优化

Spring 高级-jdk反射优化

时间:2022-09-25 15:37:00浏览次数:45  
标签:lang 反射 调用 java jdk Spring reflect class

一、代码

package com.mangoubiubiu.show.asm;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

// 运行时请添加 --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/jdk.internal.reflect=ALL-UNNAMED
public class TestMethodInvoke {


    public static void main(String[] args) throws Exception {
        Method foo = TestMethodInvoke.class.getMethod("foo", int.class);
        for (int i = 1; i <= 17; i++) {
            show(i, foo);
            foo.invoke(null, i);
        }
        System.in.read();
    }

    // 方法反射调用时, 底层 MethodAccessor 的实现类
    private static void show(int i, Method foo) throws Exception {
        Method getMethodAccessor = Method.class.getDeclaredMethod("getMethodAccessor");
        getMethodAccessor.setAccessible(true);
        Object invoke = getMethodAccessor.invoke(foo);
        if (invoke == null) {
            System.out.println(i + ":" + null);
            return;
        }
        Field delegate = Class.forName("jdk.internal.reflect.DelegatingMethodAccessorImpl").getDeclaredField("delegate");
        delegate.setAccessible(true);
        System.out.println(i + ":" + delegate.get(invoke));
    }

    public static void foo(int i) {
        System.out.println(i + ":" + "foo");
    }

}

前16次方法反射调用是用的一个实现,第17次是用的另外一个实现

用ARTHAS工具查看源码,第十七次是类型点方法名正常调用父方法

二、总结

前16次,走java 本地api 性能较低,第17次开始,动态生成代理类 ,把反射调用变成正常调用

 

 

 

 

标签:lang,反射,调用,java,jdk,Spring,reflect,class
From: https://www.cnblogs.com/mangoubiubiu/p/16727946.html

相关文章