Search in sources :

Example 1 with LocalVariableAttribute

use of javassist.bytecode.LocalVariableAttribute in project pinpoint by naver.

the class JavaAssistUtils method lookupLocalVariableAttribute.

/**
     * get LocalVariableAttribute
     *
     * @param method
     * @return null if the class is not compiled with debug option
     */
public static LocalVariableAttribute lookupLocalVariableAttribute(CtBehavior method) {
    if (method == null) {
        throw new NullPointerException("method must not be null");
    }
    MethodInfo methodInfo = method.getMethodInfo2();
    CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
    if (codeAttribute == null) {
        return null;
    }
    AttributeInfo localVariableTable = codeAttribute.getAttribute(LocalVariableAttribute.tag);
    LocalVariableAttribute local = (LocalVariableAttribute) localVariableTable;
    return local;
}
Also used : AttributeInfo(javassist.bytecode.AttributeInfo) CodeAttribute(javassist.bytecode.CodeAttribute) MethodInfo(javassist.bytecode.MethodInfo) LocalVariableAttribute(javassist.bytecode.LocalVariableAttribute)

Example 2 with LocalVariableAttribute

use of javassist.bytecode.LocalVariableAttribute in project latke by b3log.

the class Reflections method getMethodVariableNames.

/**
 * getMethodVariableNames in user defined.
 *
 * @param clazz            the specific clazz
 * @param targetMethodName the targetMethodName
 * @param types            the types of the method parameters
 * @return the String[] of names
 */
public static String[] getMethodVariableNames(final Class<?> clazz, final String targetMethodName, final Class<?>[] types) {
    CtClass cc;
    CtMethod cm = null;
    try {
        if (null == CLASS_POOL.find(clazz.getName())) {
            CLASS_POOL.insertClassPath(new ClassClassPath(clazz));
        }
        cc = CLASS_POOL.get(clazz.getName());
        final CtClass[] ptypes = new CtClass[types.length];
        for (int i = 0; i < ptypes.length; i++) {
            ptypes[i] = CLASS_POOL.get(types[i].getName());
        }
        cm = cc.getDeclaredMethod(targetMethodName, ptypes);
    } catch (final NotFoundException e) {
        LOGGER.log(Level.ERROR, "Get method variable names failed", e);
    }
    if (null == cm) {
        return new String[types.length];
    }
    final MethodInfo methodInfo = cm.getMethodInfo();
    final CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
    final LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
    String[] variableNames = new String[0];
    try {
        variableNames = new String[cm.getParameterTypes().length];
    } catch (final NotFoundException e) {
        LOGGER.log(Level.ERROR, "Get method variable names failed", e);
    }
    // final int staticIndex = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
    int j = -1;
    String variableName = null;
    Boolean ifkill = false;
    while (!"this".equals(variableName)) {
        j++;
        variableName = attr.variableName(j);
        // to prevent heap error when there being some unknown reasons to resolve the VariableNames
        if (j > MAX_FIND_LENGTH) {
            LOGGER.log(Level.WARN, "Maybe resolve to VariableNames error [class=" + clazz.getName() + ", targetMethodName=" + targetMethodName + ']');
            ifkill = true;
            break;
        }
    }
    if (!ifkill) {
        for (int i = 0; i < variableNames.length; i++) {
            variableNames[i] = attr.variableName(++j);
        }
    }
    return variableNames;
}
Also used : CodeAttribute(javassist.bytecode.CodeAttribute) MethodInfo(javassist.bytecode.MethodInfo) LocalVariableAttribute(javassist.bytecode.LocalVariableAttribute)

Example 3 with LocalVariableAttribute

use of javassist.bytecode.LocalVariableAttribute in project reflections by ronmamo.

the class MethodParameterNamesScanner method getString.

private String getString(MethodInfo method) {
    CodeAttribute codeAttribute = method.getCodeAttribute();
    LocalVariableAttribute table = codeAttribute != null ? (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag) : null;
    int length = JavassistHelper.getParameters(method).size();
    if (length > 0) {
        // skip this
        int shift = Modifier.isStatic(method.getAccessFlags()) ? 0 : 1;
        return IntStream.range(shift, length + shift).mapToObj(i -> method.getConstPool().getUtf8Info(table.nameIndex(i))).filter(name -> !name.startsWith("this$")).collect(Collectors.joining(", "));
    }
    return "";
}
Also used : IntStream(java.util.stream.IntStream) CodeAttribute(javassist.bytecode.CodeAttribute) LocalVariableAttribute(javassist.bytecode.LocalVariableAttribute) List(java.util.List) ClassFile(javassist.bytecode.ClassFile) Modifier(java.lang.reflect.Modifier) Map(java.util.Map) MethodInfo(javassist.bytecode.MethodInfo) Collectors(java.util.stream.Collectors) JavassistHelper(org.reflections.util.JavassistHelper) ArrayList(java.util.ArrayList) CodeAttribute(javassist.bytecode.CodeAttribute) LocalVariableAttribute(javassist.bytecode.LocalVariableAttribute)

Example 4 with LocalVariableAttribute

use of javassist.bytecode.LocalVariableAttribute in project dubbo-faker by moyada.

the class VariableUtil method getNameByJavassist.

// /**
// * 通过 ASM 获取属性名
// * @param clazz
// * @param method
// * @return
// * @throws IOException
// */
// public static String[] getNameByASM(Class clazz, Method method) throws IOException {
// final Class<?>[] methodParameterTypes = method.getParameterTypes();
// final int methodParameterCount = methodParameterTypes.length;
// final boolean isStatic = Modifier.isStatic(method.getModifiers());
// 
// // 读取字节码信息到ClassReader中
// ClassReader reader = new ClassReader(clazz.getName());
// ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
// 
// String[] variableName = new String[methodParameterCount];
// 
// reader.accept(new ClassVisitor(cw.hashCode(), cw) {
// /**
// * 会遍历该类的所有方法,你可以对不需要操作的方法直接返回
// */
// @Override
// public MethodVisitor visitMethod(final int access, final String name, final String desc,
// final String signature, final String[] exceptions) {
// 
// MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
// 
// final Type[] argTypes = Type.getArgumentTypes(desc);
// 
// //不需要操作的方法,直接返回,注意不要返回null,会把该方法删掉
// if (!name.equals(method.getName()) || !matchTypes(argTypes, methodParameterTypes)) {
// return mv;
// }
// 
// // 遍历该方法信息
// return new MethodVisitor(mv.hashCode(), mv) {
// 
// @Override
// public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
// //如果是静态方法,第一个参数就是方法参数,非静态方法,则第一个参数是 this ,然后才是方法的参数
// int methodParameterIndex = isStatic ? index : index - 1;
// if (0 <= methodParameterIndex && methodParameterIndex < methodParameterCount) {
// variableName[methodParameterIndex] = name;
// }
// super.visitLocalVariable(name, desc, signature, start, end, index);
// }
// };
// }
// }, 0);
// 
// return variableName;
// }
// 
// /**
// * 比较参数是否一致
// */
// 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;
// }
/**
 * 通过 javassist 获取属性名
 * @param clazz
 * @param method
 * @return
 * @throws NotFoundException
 */
public static String[] getNameByJavassist(Class clazz, Method method) throws NotFoundException {
    ClassPool classPool = ClassPool.getDefault();
    CtClass ctClass = classPool.get(clazz.getName());
    int count = method.getParameterCount();
    Class<?>[] paramTypes = method.getParameterTypes();
    CtClass[] ctParams = new CtClass[count];
    for (int i = 0; i < count; i++) {
        ctParams[i] = classPool.getCtClass(paramTypes[i].getName());
    }
    CtMethod ctMethod = ctClass.getDeclaredMethod(method.getName(), ctParams);
    // 得到该方法信息类
    MethodInfo methodInfo = ctMethod.getMethodInfo();
    // 获取属性变量相关
    CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
    if (codeAttribute == null) {
        return null;
    }
    // 获取方法本地变量信息,包括方法声明和方法体内的变量
    // 需注意,若方法为非静态方法,则第一个变量名为this
    LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
    String[] variableName = new String[count];
    int index = 0;
    int pos = 0;
    if (!Modifier.isStatic(method.getModifiers())) {
        count++;
        pos++;
    }
    for (int i = pos; i < count; i++) {
        variableName[index++] = attr.variableName(i);
    }
    return variableName;
}
Also used : CtClass(javassist.CtClass) CodeAttribute(javassist.bytecode.CodeAttribute) ClassPool(javassist.ClassPool) CtClass(javassist.CtClass) MethodInfo(javassist.bytecode.MethodInfo) LocalVariableAttribute(javassist.bytecode.LocalVariableAttribute) CtMethod(javassist.CtMethod)

Example 5 with LocalVariableAttribute

use of javassist.bytecode.LocalVariableAttribute in project leopard by tanhaichao.

the class CtClassUtil method getParameterNames.

/**
 * 获取方法的参数名称.
 *
 * @param ctMethod
 * @return
 * @throws NotFoundException
 */
public static String[] getParameterNames(CtMethod ctMethod) throws NotFoundException {
    MethodInfo methodInfo = ctMethod.getMethodInfo();
    CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
    // logger.info("methodInfo.getConstPool().getSize():");
    LocalVariableAttribute attribute = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
    // String[] names = new String[attribute.tableLength() - 1];
    String[] paramNames = new String[ctMethod.getParameterTypes().length];
    int pos = 0;
    if (true) {
        int size = attribute.tableLength();
        if (size > 0) {
            String[] names = new String[size - 1];
            for (int i = 0; i < names.length; i++) {
                names[i] = attribute.variableName(i);
                if ("this".equals(names[i])) {
                    pos = i + 1;
                    break;
                }
            }
        // logger.info(methodInfo.getName() + " pos:" + pos + " allNames:" + StringUtils.join(names, ", "));
        }
    }
    // logger.info(methodInfo.getName() + " pos:" + pos);
    for (int i = 0; i < paramNames.length; i++) {
        // paramNames[i] = attribute.variableName(i + 1);
        try {
            paramNames[i] = attribute.variableName(i + pos);
        // logger.info("paramNames[" + i + "]:" + paramNames[i]);
        } catch (RuntimeException e) {
            throw e;
        }
    }
    // System.err.println("paramNames:" + StringUtils.join(paramNames));
    return paramNames;
}
Also used : CodeAttribute(javassist.bytecode.CodeAttribute) MethodInfo(javassist.bytecode.MethodInfo) LocalVariableAttribute(javassist.bytecode.LocalVariableAttribute)

Aggregations

LocalVariableAttribute (javassist.bytecode.LocalVariableAttribute)10 MethodInfo (javassist.bytecode.MethodInfo)10 CodeAttribute (javassist.bytecode.CodeAttribute)9 CtMethod (javassist.CtMethod)3 ArrayList (java.util.ArrayList)2 ClassPool (javassist.ClassPool)2 CtClass (javassist.CtClass)2 RpcException (com.duangframework.core.exceptions.RpcException)1 Modifier (java.lang.reflect.Modifier)1 List (java.util.List)1 Map (java.util.Map)1 Collectors (java.util.stream.Collectors)1 IntStream (java.util.stream.IntStream)1 NotFoundException (javassist.NotFoundException)1 AttributeInfo (javassist.bytecode.AttributeInfo)1 ClassFile (javassist.bytecode.ClassFile)1 MetadataAdapter (org.reflections.adapters.MetadataAdapter)1 JavassistHelper (org.reflections.util.JavassistHelper)1