Search in sources :

Example 16 with MethodInfo

use of javassist.bytecode.MethodInfo in project fakereplace by fakereplace.

the class FinalMethodManipulator method transformClass.

public boolean transformClass(ClassFile file, ClassLoader loader, boolean modifiableClass, final Set<MethodInfo> modifiedMethods) {
    if (!modifiableClass) {
        return false;
    }
    boolean modified = false;
    for (Object i : file.getMethods()) {
        MethodInfo m = (MethodInfo) i;
        if ((m.getAccessFlags() & AccessFlag.FINAL) != 0) {
            m.setAccessFlags(m.getAccessFlags() & ~AccessFlag.FINAL);
            // ClassDataStore.addFinalMethod(file.getName(), m.getName(),
            // m.getDescriptor());
            AnnotationsAttribute at = (AnnotationsAttribute) m.getAttribute(AnnotationsAttribute.visibleTag);
            if (at == null) {
                at = new AnnotationsAttribute(file.getConstPool(), AnnotationsAttribute.visibleTag);
                m.addAttribute(at);
            }
            at.addAnnotation(new Annotation(ModifiedMethod.class.getName(), file.getConstPool()));
            m.addAttribute(new AttributeInfo(file.getConstPool(), Constants.FINAL_METHOD_ATTRIBUTE, new byte[0]));
            modified = true;
        }
    }
    return modified;
}
Also used : AttributeInfo(javassist.bytecode.AttributeInfo) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) MethodInfo(javassist.bytecode.MethodInfo) Annotation(javassist.bytecode.annotation.Annotation)

Example 17 with MethodInfo

use of javassist.bytecode.MethodInfo in project fakereplace by fakereplace.

the class IntegrationActivationTransformer method makeTrackedInstance.

/**
 * modifies a class so that all created instances are registered with
 * InstanceTracker
 */
private void makeTrackedInstance(ClassFile file) throws BadBytecode {
    for (MethodInfo m : (List<MethodInfo>) file.getMethods()) {
        if (m.getName().equals("<init>")) {
            Bytecode code = new Bytecode(file.getConstPool());
            code.addLdc(file.getName());
            code.addAload(0);
            code.addInvokestatic(InstanceTracker.class.getName(), "add", "(Ljava/lang/String;Ljava/lang/Object;)V");
            CodeIterator it = m.getCodeAttribute().iterator();
            it.skipConstructor();
            it.insert(code.get());
            m.getCodeAttribute().computeMaxStack();
        }
    }
}
Also used : InstanceTracker(org.fakereplace.data.InstanceTracker) CodeIterator(javassist.bytecode.CodeIterator) MethodInfo(javassist.bytecode.MethodInfo) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) BadBytecode(javassist.bytecode.BadBytecode) Bytecode(javassist.bytecode.Bytecode)

Example 18 with MethodInfo

use of javassist.bytecode.MethodInfo in project tutorials by eugenp.

the class JavasisstUnitTest method givenJavaClass_whenLoadAtByJavassist_thenTraversWholeClass.

@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"));
}
Also used : ClassFile(javassist.bytecode.ClassFile) CodeAttribute(javassist.bytecode.CodeAttribute) CodeIterator(javassist.bytecode.CodeIterator) ClassPool(javassist.ClassPool) MethodInfo(javassist.bytecode.MethodInfo) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 19 with MethodInfo

use of javassist.bytecode.MethodInfo 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 20 with MethodInfo

use of javassist.bytecode.MethodInfo 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)

Aggregations

MethodInfo (javassist.bytecode.MethodInfo)54 Bytecode (javassist.bytecode.Bytecode)28 BadBytecode (javassist.bytecode.BadBytecode)19 CodeIterator (javassist.bytecode.CodeIterator)18 CodeAttribute (javassist.bytecode.CodeAttribute)17 ConstPool (javassist.bytecode.ConstPool)17 ClassFile (javassist.bytecode.ClassFile)12 LocalVariableAttribute (javassist.bytecode.LocalVariableAttribute)10 DuplicateMemberException (javassist.bytecode.DuplicateMemberException)9 List (java.util.List)7 ClassPool (javassist.ClassPool)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 DataOutputStream (java.io.DataOutputStream)6 IOException (java.io.IOException)6 CtMethod (javassist.CtMethod)6 HashMap (java.util.HashMap)5 HashSet (java.util.HashSet)5 Set (java.util.Set)5 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)5 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)4