Javassist初探

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuzhixiong_521/article/details/83898890

文章目录

概述

Javassist是一款字节码编辑工具,可以直接编辑和生成Java生成的字节码,以达到对.class文件进行动态修改的效果。熟练使用这套工具,可以让Java编程更接近与动态语言编程。今天我们使用Javassist获取形参名以及实参值对应表。

准备

pom引入依赖包

<dependency>
	<groupId>javassist</groupId>
	<artifactId>javassist</artifactId>
	<version>3.12.1.GA</version>
</dependency>

实现

public static Map<String, Object> getTypeAndValues(Class clazz, Method method, Object[] args) {
    Map<String, Object> typeAndValue = new HashMap<String, Object>();
    try {
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.get(clazz.getName());
        String name = method.getName();
        CtMethod ctm = cc.getDeclaredMethod(name);
        MethodInfo methodInfo = ctm.getMethodInfo();
        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
        LocalVariableAttribute attribute = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
        int pos = Modifier.isStatic(ctm.getModifiers()) ? 0 : 1;
        for (int i = 0; i < ctm.getParameterTypes().length; i++) {
            typeAndValue.put(attribute.variableName(i + pos).toLowerCase(), args[i]);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return typeAndValue;
}

问题

在tomcat下有时候找不到相应class字节码,只需要在ClassPool pool = ClassPool.getDefault()这行代码下加入ClassPath路径即可:

ClassClassPath classPath = new ClassClassPath(clazz);
pool.insertClassPath(classPath);

猜你喜欢

转载自blog.csdn.net/liuzhixiong_521/article/details/83898890