Java Code Examples for javassist.bytecode.MethodInfo#getCodeAttribute()

The following examples show how to use javassist.bytecode.MethodInfo#getCodeAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReflectUtil.java    From koper with Apache License 2.0 7 votes vote down vote up
/**
 * Get method arg names.
 *
 * @param clazz
 * @param methodName
 * @return
 */
public static <T> String[] getMethodArgNames(Class<T> clazz, String methodName) {
    try {
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.get(clazz.getName());

        CtMethod cm = cc.getDeclaredMethod(methodName);

        // 使用javaassist的反射方法获取方法的参数名
        MethodInfo methodInfo = cm.getMethodInfo();
        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
        LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
        if (attr == null) {
            throw new RuntimeException("LocalVariableAttribute of method is null! Class " + clazz.getName() + ",method name is " + methodName);
        }
        String[] paramNames = new String[cm.getParameterTypes().length];
        int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
        for (int i = 0; i < paramNames.length; i++)
            paramNames[i] = attr.variableName(i + pos);

        return paramNames;
    } catch (NotFoundException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 2
Source File: ReflectionUtils.java    From cola-cloud with MIT License 6 votes vote down vote up
private static String[] getMethodParamNames(CtMethod ctMethod) throws RuntimeException {
    CtClass ctClass = ctMethod.getDeclaringClass();
    MethodInfo methodInfo = ctMethod.getMethodInfo();
    CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
    LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
    if (attr == null) {
        throw new RuntimeException(ctClass.getName());
    }
    try {
        String[] paramNames = new String[ctMethod.getParameterTypes().length];
        int pos = Modifier.isStatic(ctMethod.getModifiers()) ? 0 : 1;
        for (int i = 0; i < paramNames.length; i++) {
            paramNames[i] = attr.variableName(i + pos);
        }
        return paramNames;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source File: MethodParameterName.java    From Summer with Apache License 2.0 6 votes vote down vote up
public String[] getParameterNameByMethod(Method method) throws NotFoundException {
	CtMethod ctm = ct.getDeclaredMethod(method.getName());
	MethodInfo methodInfo = ctm.getMethodInfo();
	CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
	LocalVariableAttribute attr = (LocalVariableAttribute)codeAttribute.getAttribute(LocalVariableAttribute.tag);
	String[] params = null;
	if (attr != null) {
		int len = ctm.getParameterTypes().length;
		params = new String[len];
		TreeMap<Integer, String> sortMap = Maps.newTreeMap();
		for (int i = 0; i < attr.tableLength(); i++)
			sortMap.put(attr.index(i), attr.variableName(i));
		int pos = Modifier.isStatic(ctm.getModifiers()) ? 0 : 1;
		params = Arrays.copyOfRange(sortMap.values().toArray(new String[0]), pos, params.length + pos);
	}
	return params;
}
 
Example 4
Source File: ClassHelper.java    From TakinRPC with Apache License 2.0 6 votes vote down vote up
/**
 * get method parameter names
 * @param cls
 * @param method
 * @return
 * @throws Exception
 */
public static String[] getParamNames(Class<?> cls, Method method) throws Exception {
    ClassPool pool = ClassPool.getDefault();
    CtClass cc = pool.get(cls.getName());

    Class<?>[] paramAry = method.getParameterTypes();
    String[] paramTypeNames = new String[paramAry.length];
    for (int i = 0; i < paramAry.length; i++) {
        paramTypeNames[i] = paramAry[i].getName();
    }

    CtMethod cm = cc.getDeclaredMethod(method.getName(), pool.get(paramTypeNames));

    MethodInfo methodInfo = cm.getMethodInfo();
    CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
    LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
    if (attr == null) {
        throw new Exception("class:" + cls.getName() + ", have no LocalVariableTable, please use javac -g:{vars} to compile the source file");
    }
    String[] paramNames = new String[cm.getParameterTypes().length];
    int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
    for (int i = 0; i < paramNames.length; i++) {
        paramNames[i] = attr.variableName(i + pos);
    }
    return paramNames;
}
 
Example 5
Source File: HandlerMethodArgsBuilder.java    From potato-webmvc with MIT License 6 votes vote down vote up
private void initMethodParamInfo(Object controller, String methodName) {
	methodParamInfo = new LinkedHashMap<Class<?>, String>();
	Class<?> clazz = controller.getClass();
	try {
		ClassPool classPool = ClassPool.getDefault();
		classPool.insertClassPath(new ClassClassPath(clazz));
		CtClass ctClass = classPool.get(clazz.getName());
		CtMethod ctMethod = ctClass.getDeclaredMethod(methodName);

		MethodInfo methodInfo = ctMethod.getMethodInfo();
		CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
		LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
				.getAttribute("LocalVariableTable");

		CtClass[] parameterTypes = ctMethod.getParameterTypes();
		int pos = Modifier.isStatic(ctMethod.getModifiers()) ? 0 : 1;
		for (int i = 0; i < parameterTypes.length; i++)
			methodParamInfo.put(Class.forName(parameterTypes[i].getName()),
					attr.variableName(i + pos));
	} catch (Exception e) {
		throw new RuntimeException(e.getMessage());
	}
}
 
Example 6
Source File: BeanUtil.java    From framework with Apache License 2.0 6 votes vote down vote up
/**
 * 获取方法参数名称
 * 
 * @param cm <br>
 * @return <br>
 * @throws NotFoundException <br>
 * @throws UtilException 如果最终编译的class文件不包含局部变量表信息 <br>
 */
protected static String[] getMethodParamNames(final CtMethod cm) throws NotFoundException, UtilException {
    CtClass cc = cm.getDeclaringClass();
    MethodInfo methodInfo = cm.getMethodInfo();
    CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
    if (codeAttribute == null) {
        throw new UtilException(ErrorCodeDef.CAN_NOT_FIND_VER_NAME_10003, cc.getName());
    }
    LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
    if (null == attr) {
        throw new UtilException(ErrorCodeDef.CAN_NOT_FIND_VER_NAME_10003, cc.getName());
    }
    String[] paramNames = new String[cm.getParameterTypes().length];
    int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
    for (int i = 0; i < paramNames.length; i++) {
        paramNames[i] = attr.variableName(i + pos);
    }
    return paramNames;
}
 
Example 7
Source File: JavasisstUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenJavaClass_whenLoadAtByJavassist_thenTraversWholeClass() throws NotFoundException, CannotCompileException, BadBytecode {
    // given
    ClassPool cp = ClassPool.getDefault();
    ClassFile cf = cp.get("com.baeldung.javasisst.Point").getClassFile();
    MethodInfo minfo = cf.getMethod("move");
    CodeAttribute ca = minfo.getCodeAttribute();
    CodeIterator ci = ca.iterator();

    // when
    List<String> operations = new LinkedList<>();
    while (ci.hasNext()) {
        int index = ci.next();
        int op = ci.byteAt(index);
        operations.add(Mnemonic.OPCODE[op]);
    }

    // then
    assertEquals(operations, Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return"));

}
 
Example 8
Source File: ClassUtil.java    From common-project with Apache License 2.0 5 votes vote down vote up
/**
 * 基于javassist获取类方法参数名称
 * @param method
 * @return
 * @throws Exception
 */
public static String[] getMethodParamsName(Method method) throws Exception{
    Class<?> clazz = method.getDeclaringClass();
    ClassPool pool = ClassPool.getDefault();
    CtClass clz = pool.get(clazz.getName());
    CtClass[] params = new CtClass[method.getParameterTypes().length];
    for (int i = 0; i < method.getParameterTypes().length; i++) {
        params[i] = pool.getCtClass(method.getParameterTypes()[i].getName());
    }
    CtMethod cm = clz.getDeclaredMethod(method.getName(), params);
    MethodInfo methodInfo = cm.getMethodInfo();
    CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
    if (codeAttribute==null) {
        return null;
    }
    LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
            .getAttribute(LocalVariableAttribute.tag);
    int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
    String[] paramNames = new String[cm.getParameterTypes().length];
    if (attr==null) {
        return null;
    }
    for (int i = 0; i < paramNames.length; i++) {
        paramNames[i] = attr.variableName(i + pos);
    }
    return paramNames;
}
 
Example 9
Source File: FieldTransformer.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void transformInvokevirtualsIntoPutAndGetfields(ClassFile classfile)
		throws CannotCompileException {
	List methods = classfile.getMethods();
	for (Iterator method_iter = methods.iterator(); method_iter.hasNext();) {
		MethodInfo minfo = (MethodInfo) method_iter.next();
		String methodName = minfo.getName();
		if (methodName.startsWith(EACH_READ_METHOD_PREFIX)
		    || methodName.startsWith(EACH_WRITE_METHOD_PREFIX)
		    || methodName.equals(GETFIELDHANDLER_METHOD_NAME)
		    || methodName.equals(SETFIELDHANDLER_METHOD_NAME)) {
			continue;
		}
		CodeAttribute codeAttr = minfo.getCodeAttribute();
		if (codeAttr == null) {
			return;
		}
		CodeIterator iter = codeAttr.iterator();
		while (iter.hasNext()) {
			try {
				int pos = iter.next();
				pos = transformInvokevirtualsIntoGetfields(classfile, iter,
				                                           pos);
				pos = transformInvokevirtualsIntoPutfields(classfile, iter,
				                                           pos);

			} catch (BadBytecode e) {
				throw new CannotCompileException(e);
			}
		}
	}
}
 
Example 10
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
private CodeAttribute getMethodCodeAttribute(Signature methodSignature) 
throws MethodNotFoundException, MethodCodeNotFoundException {
    final MethodInfo m = findMethodDeclaration(methodSignature);
    if (m == null) { 
        throw new MethodNotFoundException(methodSignature.toString());
    }
    final CodeAttribute ca = m.getCodeAttribute();
    if (ca == null) {
        throw new MethodCodeNotFoundException(methodSignature.toString()); 
    }
    return ca;
}
 
Example 11
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean hasMethodImplementation(Signature methodSignature) {
    final MethodInfo m = findMethodDeclaration(methodSignature);
    return (m != null && (m.getCodeAttribute() != null || Modifier.isNative(AccessFlag.toModifier(m.getAccessFlags()))));
}