Search in sources :

Example 6 with CodeAttribute

use of javassist.bytecode.CodeAttribute in project yyl_example by Relucent.

the class GetMethodParamNameTest method getMethodParamNames.

/**
	 * 获得参数名 (JDK 自带类 ,接口方法和抽象方法无法正确获取参数名)
	 */
private static String[] getMethodParamNames(final Method method) throws NotFoundException {
    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 = new String[methodParameterCount];
    ClassPool pool = ClassPool.getDefault();
    CtClass ctClass = pool.get(className);
    CtClass[] ctTypes = new CtClass[methodParameterTypes.length];
    for (int i = 0; i < methodParameterCount; i++) {
        ctTypes[i] = pool.get(methodParameterTypes[i].getName());
    }
    CtMethod ctMethod = ctClass.getDeclaredMethod(methodName, ctTypes);
    MethodInfo methodInfo = ctMethod.getMethodInfo();
    CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
    LocalVariableAttribute attribute = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
    //如果是静态方法,第一个参数就是方法参数,非静态方法,则第一个参数是 this ,然后才是方法的参数
    if (attribute != null) {
        int variableCount = isStatic ? methodParameterCount : methodParameterCount + 1;
        for (int index = 0; index < variableCount; index++) {
            int methodParameterIndex = isStatic ? index : index - 1;
            if (0 <= methodParameterIndex && methodParameterIndex < methodParameterCount) {
                methodParametersNames[methodParameterIndex] = attribute.variableName(index);
            }
        }
    }
    return methodParametersNames;
}
Also used : ClassPool(javassist.ClassPool) CtClass(javassist.CtClass) CodeAttribute(javassist.bytecode.CodeAttribute) CtClass(javassist.CtClass) MethodInfo(javassist.bytecode.MethodInfo) LocalVariableAttribute(javassist.bytecode.LocalVariableAttribute) CtMethod(javassist.CtMethod)

Aggregations

CodeAttribute (javassist.bytecode.CodeAttribute)6 CtClass (javassist.CtClass)4 Bytecode (javassist.bytecode.Bytecode)4 CannotCompileException (javassist.CannotCompileException)3 NotFoundException (javassist.NotFoundException)3 BadBytecode (javassist.bytecode.BadBytecode)3 CodeIterator (javassist.bytecode.CodeIterator)3 MethodInfo (javassist.bytecode.MethodInfo)3 CompileError (javassist.compiler.CompileError)3 Javac (javassist.compiler.Javac)3 ConstPool (javassist.bytecode.ConstPool)2 LocalVariableAttribute (javassist.bytecode.LocalVariableAttribute)2 ClassPool (javassist.ClassPool)1 CtMethod (javassist.CtMethod)1 AttributeInfo (javassist.bytecode.AttributeInfo)1 StackMapTable (javassist.bytecode.StackMapTable)1