使用javassist对类做字节码增强

业务背景

在日常开发中我们依赖的三方库里的类是无法改动的. 但可以使用javassist 在启动时对类的字节码做改动.达到修改类的作用

实现方式

java 复制代码
@Slf4j
public class JeeSiteJavassistShiroByteCode {

    public static void install() {
        try {
            ClassPool pool = ClassPool.getDefault();
            CtClass cc = pool.get("com.jeesite.common.mybatis.mapper.xmltags.IiIiiiiIiiiI");
            cc.defrost();
            CtMethod m = cc.getDeclaredMethod("doGetAuthenticationInfo");
            CtMethod m2 = cc.getDeclaredMethod("getAuthorizationInfo");
            m.insertAfter("{ System.out.println(\"doGetAuthenticationInfo: \"+com.alibaba.fastjson.JSONObject.toJSONString($_)+\"  :   \"+com.alibaba.fastjson.JSONObject.toJSONString($1)); }");
            m2.insertAfter("{ System.out.println(\"getAuthorizationInfo: \"+com.alibaba.fastjson.JSONObject.toJSONString($_)+\"  :   \"+com.alibaba.fastjson.JSONObject.toJSONString($1)); }");
            cc.writeFile(".");
            cc.toClass();
        } catch (Exception e) {
            log.error("bytecode modify failed.", e);
        }
    }
}

利用javassist 可以将方法的入参和返回值打印出来.

启用javassist

java 复制代码
   public static void main(String[] args) {
        JeeSiteJavassistShiroByteCode.install();
        SpringApplication.run(MesApplication.class, args);
    }

在启动之前对类的字节码做修改

相关推荐
only-qi4 小时前
146. LRU 缓存
java·算法·缓存
xuxie135 小时前
SpringBoot文件下载(多文件以zip形式,单文件格式不变)
java·spring boot·后端
重生成为编程大王5 小时前
Java中的多态有什么用?
java·后端
666和7775 小时前
Struts2 工作总结
java·数据库
中草药z5 小时前
【Stream API】高效简化集合处理
java·前端·javascript·stream·parallelstream·并行流
野犬寒鸦5 小时前
力扣hot100:搜索二维矩阵 II(常见误区与高效解法详解)(240)
java·数据结构·算法·leetcode·面试
zru_96025 小时前
centos 系统如何安装open jdk 8
java·linux·centos
LiRuiJie6 小时前
深入剖析Spring Boot / Spring 应用中可自定义的扩展点
java·spring boot·spring