java asm获取常量class_使用ASM获得JAVA类方法参数名

packageyyl.example.demo.asm;importjava.io.IOException;importjava.lang.reflect.Method;importjava.lang.reflect.Modifier;importjava.util.Arrays;importorg.objectweb.asm.ClassAdapter;importorg.objectweb.asm.ClassReader;importorg.objectweb.asm.ClassWriter;importorg.objectweb.asm.Label;importorg.objectweb.asm.MethodAdapter;importorg.objectweb.asm.MethodVisitor;importorg.objectweb.asm.Type;/*** 使用ASM获得JAVA类方法参数名*/

public classGetMethodParamNameTest {static classTest {voidmethod(String name, Object value) {

}

}public static void main(String[] args) throwsSecurityException, NoSuchMethodException, IOException {

Method method1= Test.class.getDeclaredMethod("method", String.class, Object.class);

System.out.println(Arrays.toString(getMethodParamNames(method)));

}/**使用字节码工具ASM来获取方法的参数名*/

public static String[] getMethodParamNames(final Method method) throwsIOException {final String methodName =method.getName();final Class>[] methodParameterTypes =method.getParameterTypes();final int methodParameterCount =methodParameterTypes.length;final String className =method.getDeclaringClass().getName();final boolean isStatic =Modifier.isStatic(method.getModifiers());final String[] methodParametersNames = newString[methodParameterCount];

ClassReader cr= newClassReader(className);

ClassWriter cw= newClassWriter(ClassWriter.COMPUTE_MAXS);

cr.accept(newClassAdapter(cw) {public MethodVisitor visitMethod(intaccess, String name, String desc, String signature, String[] exceptions) {

MethodVisitor mv= super.visitMethod(access, name, desc, signature, exceptions);final Type[] argTypes =Type.getArgumentTypes(desc);//参数类型不一致

if (!methodName.equals(name) || !matchTypes(argTypes, methodParameterTypes)) {returnmv;

}return newMethodAdapter(mv) {public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, intindex) {//如果是静态方法,第一个参数就是方法参数,非静态方法,则第一个参数是 this ,然后才是方法的参数

int methodParameterIndex = isStatic ? index : index - 1;if (0 <= methodParameterIndex && methodParameterIndex

methodParametersNames[methodParameterIndex]=name;

}super.visitLocalVariable(name, desc, signature, start, end, index);

}

};

}

},0);returnmethodParametersNames;

}/*** 比较参数是否一致*/

private static boolean matchTypes(Type[] types, Class>[] parameterTypes) {if (types.length !=parameterTypes.length) {return false;

}for (int i = 0; i < types.length; i++) {if (!Type.getType(parameterTypes[i]).equals(types[i])) {return false;

}

}return true;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值