Example usage for org.objectweb.asm MethodVisitor visitEnd

List of usage examples for org.objectweb.asm MethodVisitor visitEnd

Introduction

In this page you can find the example usage for org.objectweb.asm MethodVisitor visitEnd.

Prototype

public void visitEnd() 

Source Link

Document

Visits the end of the method.

Usage

From source file:com.lighters.asm.HelloWorld.java

License:Apache License

public static void main(final String args[]) throws Exception {
    // Generates the bytecode corresponding to the following Java class:
    ///*from ww w.j ava 2 s  . c om*/
    // public class Example {
    // public static void main (String[] args) {
    // System.out.println("Hello world!");
    // }
    // }

    // creates a ClassWriter for the Example public class,
    // which inherits from Object
    ClassWriter cw = new ClassWriter(0);
    cw.visit(V1_1, ACC_PUBLIC, "Example", null, "java/lang/Object", null);

    // creates a MethodWriter for the (implicit) constructor
    MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    // pushes the 'this' variable
    mw.visitVarInsn(ALOAD, 0);
    // invokes the super class constructor
    mw.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
    mw.visitInsn(RETURN);
    // this code uses a maximum of one stack element and one local variable
    mw.visitMaxs(1, 1);
    mw.visitEnd();

    // creates a MethodWriter for the 'main' method
    mw = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
    // pushes the 'out' field (of type PrintStream) of the System class
    mw.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
    // pushes the "Hello World!" String constant
    mw.visitLdcInsn("Hello world!");
    // invokes the 'println' method (defined in the PrintStream class)
    mw.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
    mw.visitInsn(RETURN);
    // this code uses a maximum of two stack elements and two local
    // variables
    mw.visitMaxs(2, 2);
    mw.visitEnd();

    // gets the bytecode of the Example class, and loads it dynamically
    byte[] code = cw.toByteArray();

    FileOutputStream fos = new FileOutputStream("Example.class");
    fos.write(code);
    fos.close();

    HelloWorld loader = new HelloWorld();
    Class<?> exampleClass = loader.defineClass("Example", code, 0, code.length);

    // uses the dynamically generated class to print 'Helloworld'
    exampleClass.getMethods()[0].invoke(null, new Object[] { null });

    // ------------------------------------------------------------------------
    // Same example with a GeneratorAdapter (more convenient but slower)
    // ------------------------------------------------------------------------

    cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    cw.visit(V1_1, ACC_PUBLIC, "Example", null, "java/lang/Object", null);

    // creates a GeneratorAdapter for the (implicit) constructor
    Method m = Method.getMethod("void <init> ()");
    GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cw);
    mg.loadThis();
    mg.invokeConstructor(Type.getType(Object.class), m);
    mg.returnValue();
    mg.endMethod();

    // creates a GeneratorAdapter for the 'main' method
    m = Method.getMethod("void main (String[])");
    mg = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, m, null, null, cw);
    mg.getStatic(Type.getType(System.class), "out", Type.getType(PrintStream.class));
    mg.push("Hello world!");
    mg.invokeVirtual(Type.getType(PrintStream.class), Method.getMethod("void println (String)"));
    mg.returnValue();
    mg.endMethod();

    cw.visitEnd();

    code = cw.toByteArray();
    loader = new HelloWorld();
    exampleClass = loader.defineClass("Example", code, 0, code.length);

    // uses the dynamically generated class to print 'Helloworld'
    exampleClass.getMethods()[0].invoke(null, new Object[] { null });
}

From source file:com.lucidtechnics.blackboard.TargetConstructor.java

License:Apache License

private static final byte[] createWrapperObjectByteArray(String _targetName, Class _class) {
    ClassWriter classWriter = new ClassWriter(true);

    FieldVisitor fieldVisitor;/*from  w w w  . j  a  va 2s .c o m*/
    MethodVisitor methodVisitor;
    String superClassName = _class.getCanonicalName().replaceAll("\\.", "/");

    String[] superClassNameParts = superClassName.split("/");
    String simpleClassName = superClassNameParts[superClassNameParts.length - 1];
    String blackboardSubClassName = "com/lucidtechnics/blackboard/wrapper/" + superClassName + "Wrapper";

    classWriter.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, blackboardSubClassName, null,
            superClassName, new String[] { "com/lucidtechnics/blackboard/Target" });

    classWriter.visitSource(simpleClassName, null);

    {
        fieldVisitor = classWriter.visitField(Opcodes.ACC_PRIVATE, "blackboardObject", "Ljava/lang/Object;",
                null, null);
        fieldVisitor.visitEnd();
    }

    {
        fieldVisitor = classWriter.visitField(Opcodes.ACC_PRIVATE, "intercepter",
                "Lcom/lucidtechnics/blackboard/Intercepter;", null, null);
        fieldVisitor.visitEnd();
    }

    {
        methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "getBlackboardObject",
                "()Ljava/lang/Object;", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitFieldInsn(Opcodes.GETFIELD, blackboardSubClassName, "blackboardObject",
                "Ljava/lang/Object;");
        methodVisitor.visitInsn(Opcodes.ARETURN);
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
    }

    {
        methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "getIntercepter",
                "()Lcom/lucidtechnics/blackboard/Intercepter;", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitFieldInsn(Opcodes.GETFIELD, blackboardSubClassName, "intercepter",
                "Lcom/lucidtechnics/blackboard/Intercepter;");
        methodVisitor.visitInsn(Opcodes.ARETURN);
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
    }

    {
        methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "setBlackboardObject",
                "(Ljava/lang/Object;)V", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, blackboardSubClassName, "blackboardObject",
                "Ljava/lang/Object;");
        methodVisitor.visitInsn(Opcodes.RETURN);
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
    }

    {
        methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "setIntercepter",
                "(Lcom/lucidtechnics/blackboard/Intercepter;)V", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, blackboardSubClassName, "intercepter",
                "Lcom/lucidtechnics/blackboard/Intercepter;");
        methodVisitor.visitInsn(Opcodes.RETURN);
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
    }

    {
        methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClassName, "<init>", "()V");
        methodVisitor.visitInsn(Opcodes.RETURN);
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
    }

    List mutatorMethodList = findMutatorMethods(_class);

    Iterator mutatorMethods = mutatorMethodList.iterator();

    while (mutatorMethods.hasNext() == true) {
        Method method = (Method) mutatorMethods.next();
        MethodInfo methodInfo = (MethodInfo) MethodInfoTransformer.getInstance().transform(method);
        Signature signature = methodInfo.getSignature();
        String methodName = signature.getName();

        String parameterType = signature.getArgumentTypes()[0].getDescriptor();
        String returnType = signature.getReturnType().getDescriptor();
        String[] exceptionTypeArray = createExceptionTypeArray(methodInfo.getExceptionTypes());

        {
            methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, methodName,
                    "(" + parameterType + ")" + returnType, null, exceptionTypeArray);

            methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
            methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, blackboardSubClassName, "getIntercepter",
                    "()Lcom/lucidtechnics/blackboard/Intercepter;");
            Label l1 = new Label();
            methodVisitor.visitJumpInsn(Opcodes.IFNULL, l1);

            methodVisitor.visitCode();
            methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
            methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, blackboardSubClassName, "getIntercepter",
                    "()Lcom/lucidtechnics/blackboard/Intercepter;");

            methodVisitor.visitLdcInsn(superClassName);
            methodVisitor.visitLdcInsn(blackboardSubClassName);
            methodVisitor.visitLdcInsn(methodName);
            methodVisitor.visitLdcInsn(_targetName);
            methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);

            int tempOpCode = getLoadOpcode(parameterType);
            methodVisitor.visitVarInsn(tempOpCode, 1);

            if (tempOpCode == Opcodes.ALOAD) {
                //this is an object.
                methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE,
                        "com/lucidtechnics/blackboard/Intercepter", "monitor",
                        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V");
            } else {
                //it is a primitive.
                methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE,
                        "com/lucidtechnics/blackboard/Intercepter", "monitor",
                        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;"
                                + parameterType + ")V");
            }

            methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
            methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, blackboardSubClassName, "getBlackboardObject",
                    "()Ljava/lang/Object;");
            methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, superClassName);
            methodVisitor.visitVarInsn(getLoadOpcode(parameterType), 1);
            methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, superClassName, methodName,
                    "(" + parameterType + ")" + returnType);

            methodVisitor.visitLabel(l1);

            methodVisitor.visitInsn(getReturnOpcode(returnType));
            methodVisitor.visitMaxs(0, 0);
            methodVisitor.visitEnd();
        }
    }

    List otherPublicMethodList = findOtherPublicMethods(_class);

    Iterator otherPublicMethods = otherPublicMethodList.iterator();

    while (otherPublicMethods.hasNext() == true) {
        Method method = (Method) otherPublicMethods.next();
        MethodInfo methodInfo = (MethodInfo) MethodInfoTransformer.getInstance().transform(method);
        Signature signature = methodInfo.getSignature();
        String methodName = signature.getName();

        String parameterTypes = constructParameterTypes(signature.getArgumentTypes());
        String returnType = signature.getReturnType().getDescriptor();
        String[] exceptionTypeArray = createExceptionTypeArray(methodInfo.getExceptionTypes());

        if (logger.isDebugEnabled() == true) {
            logger.debug("Processing method: " + methodName);
        }
        if (logger.isDebugEnabled() == true) {
            logger.debug("Parameter types are: " + parameterTypes);
        }

        if ("toString".equalsIgnoreCase(methodName) == false) {
            methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, methodName,
                    "(" + parameterTypes + ")" + returnType, null, exceptionTypeArray);

            methodVisitor.visitCode();
            methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
            methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, blackboardSubClassName, "getBlackboardObject",
                    "()Ljava/lang/Object;");
            methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, superClassName);
            methodVisitor.visitVarInsn(Opcodes.ASTORE, signature.getArgumentTypes().length + 1);
            methodVisitor.visitVarInsn(Opcodes.ALOAD, signature.getArgumentTypes().length + 1);

            loadParameters(methodVisitor, signature.getArgumentTypes());

            methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, superClassName, methodName,
                    "(" + parameterTypes + ")" + returnType);
            methodVisitor.visitInsn(getReturnOpcode(returnType));
            methodVisitor.visitMaxs(0, 0);
            methodVisitor.visitEnd();
        }
    }

    List protectedMethodList = findProtectedMethods(_class);

    Iterator protectedMethods = protectedMethodList.iterator();

    while (protectedMethods.hasNext() == true) {
        Method method = (Method) protectedMethods.next();
        MethodInfo methodInfo = (MethodInfo) MethodInfoTransformer.getInstance().transform(method);
        Signature signature = methodInfo.getSignature();
        String methodName = signature.getName();

        String parameterTypes = constructParameterTypes(signature.getArgumentTypes());
        String returnType = signature.getReturnType().getDescriptor();
        String[] exceptionTypeArray = createExceptionTypeArray(methodInfo.getExceptionTypes());

        if (logger.isDebugEnabled() == true) {
            logger.debug("Processing method: " + methodName + " and parameter types are: " + parameterTypes);
        }

        {
            methodVisitor = classWriter.visitMethod(Opcodes.ACC_PROTECTED, methodName,
                    "(" + parameterTypes + ")" + returnType, null, exceptionTypeArray);

            methodVisitor.visitCode();
            methodVisitor.visitTypeInsn(Opcodes.NEW, "com/lucidtechnics/blackboard/BlackboardException");
            methodVisitor.visitInsn(Opcodes.DUP);
            methodVisitor.visitLdcInsn("Unable to access protected methods on Blackboard object");
            methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL,
                    "com/lucidtechnics/blackboard/BlackboardException", "<init>", "(Ljava/lang/String;)V");
            methodVisitor.visitInsn(Opcodes.ATHROW);
            methodVisitor.visitMaxs(0, 0);
            methodVisitor.visitEnd();
        }
    }

    {
        methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "toString", "()Ljava/lang/String;", null,
                null);
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, blackboardSubClassName, "getBlackboardObject",
                "()Ljava/lang/Object;");
        methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "com/lucidtechnics/blackboard/util/Utility",
                "toString", "(Ljava/lang/Object;)Ljava/lang/String;");
        methodVisitor.visitInsn(getReturnOpcode("Ljava/lang/String;"));
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
    }

    classWriter.visitEnd();

    if (logger.isDebugEnabled() == true) {
        logger.debug("Finished creating new class: " + blackboardSubClassName + " for target class: "
                + superClassName + ".");
    }

    return classWriter.toByteArray();
}

From source file:com.mogujie.instantrun.IncrementalChangeVisitor.java

License:Apache License

/**
 * Turns this class into an override class that can be loaded by our custom class loader:
 * <ul>//  ww w .  j av a 2s .co  m
 * <li>Make the class name be OriginalName$override</li>
 * <li>Ensure the class derives from java.lang.Object, no other inheritance</li>
 * <li>Ensure the class has a public parameterless constructor that is a noop.</li>
 * </ul>
 */
@Override
public void visit(int version, int access, String name, String signature, String superName,
        String[] interfaces) {
    super.visit(version, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, name + OVERRIDE_SUFFIX, signature,
            "java/lang/Object", new String[] { CHANGE_TYPE.getInternalName() });

    visitedClassName = name;
    visitedSuperName = superName;
    instanceToStaticDescPrefix = "(L" + visitedClassName + ";";

    // Create empty constructor
    MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();

    //        super.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_STATIC,
    //                "$obsolete", "Z", null, null);
}

From source file:com.mogujie.instantrun.IncrementalChangeVisitor.java

License:Apache License

public void addSupportMethod() {
    int access = Opcodes.ACC_PUBLIC;
    Method m = new Method("isSupport", "(I)Z");
    MethodVisitor mv = super.visitMethod(access, m.getName(), m.getDescriptor(), null, null);

    mv.visitCode();/*from ww w . j  a  v  a  2  s. com*/
    mv.visitVarInsn(Opcodes.ALOAD, 1);
    //        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "hashCode", "()I", false);

    int[] hashArray = new int[fixMtds.size()];
    Label[] labelArray = new Label[fixMtds.size()];
    Label l0 = new Label();
    Label l1 = new Label();
    for (int i = 0; i < fixMtds.size(); i++) {
        hashArray[i] = AcesoProguardMap.instance().getClassData(visitedClassName).getMtdIndex(fixMtds.get(i));
        labelArray[i] = l0;
    }

    mv.visitLookupSwitchInsn(l1, hashArray, labelArray);
    mv.visitLabel(l0);
    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
    mv.visitInsn(Opcodes.ICONST_1);
    mv.visitInsn(Opcodes.IRETURN);
    mv.visitLabel(l1);
    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
    mv.visitInsn(Opcodes.ICONST_0);
    mv.visitInsn(Opcodes.IRETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    mv.visitMaxs(0, 0);
    mv.visitEnd();

}

From source file:com.mogujie.instantrun.IncrementalTool.java

License:Apache License

public static byte[] getPatchFileContents(ImmutableList<String> patchFileContents,
        ImmutableList<Integer> patchIndexContents) {
    if (patchFileContents.size() != patchIndexContents.size()) {
        throw new GradleException("patchFileContents's size is " + patchFileContents.size()
                + ", but patchIndexContents's size is " + patchIndexContents.size()
                + ", please check the changed classes.");
    }/*w w  w  .j a  v  a2  s.c  o  m*/
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, IncrementalVisitor.APP_PATCHES_LOADER_IMPL,
            null, IncrementalVisitor.ABSTRACT_PATCHES_LOADER_IMPL, null);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, IncrementalVisitor.ABSTRACT_PATCHES_LOADER_IMPL, "<init>",
                "()V", false);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getPatchedClasses", "()[Ljava/lang/String;", null, null);
        mv.visitCode();

        mv.visitIntInsn(Opcodes.SIPUSH, patchFileContents.size());
        mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
        for (int index = 0; index < patchFileContents.size(); index++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.SIPUSH, index);
            mv.visitLdcInsn(patchFileContents.get(index));
            mv.visitInsn(Opcodes.AASTORE);
        }
        mv.visitInsn(Opcodes.ARETURN);
        mv.visitMaxs(4, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getPatchedClassIndexes", "()[I", null, null);
        mv.visitCode();

        mv.visitIntInsn(Opcodes.SIPUSH, patchIndexContents.size());
        mv.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_INT);
        for (int index = 0; index < patchIndexContents.size(); index++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.SIPUSH, index);
            mv.visitLdcInsn(patchIndexContents.get(index));
            mv.visitInsn(Opcodes.IASTORE);
        }
        mv.visitInsn(Opcodes.ARETURN);
        mv.visitMaxs(4, 1);
        mv.visitEnd();
    }
    cw.visitEnd();

    return cw.toByteArray();

}

From source file:com.mogujie.instantrun.SuperHelperVisitor.java

License:Apache License

public void start() {
    visit(Opcodes.V1_7, ACC_PUBLIC + ACC_SUPER, visitor.visitedClassName + "$helper", null,
            visitor.visitedSuperName, null);
    for (int nodeIndex = 0; nodeIndex < superNode.methods.size(); nodeIndex++) {
        MethodNode methodNode = (MethodNode) superNode.methods.get(nodeIndex);
        if ("<init>".equals(methodNode.name)) {
            String[] exceptions = null;
            if (methodNode.exceptions != null) {
                exceptions = (String[]) methodNode.exceptions.toArray(new String[0]);
            }//from  w w w .j a va2s. com
            MethodVisitor mv = visitMethod(ACC_PUBLIC, methodNode.name, methodNode.desc, methodNode.signature,
                    exceptions);
            mv.visitCode();
            Type[] args = Type.getArgumentTypes(methodNode.desc);
            List<LocalVariable> variables = ByteCodeUtils.toLocalVariables(Arrays.asList(args));
            mv.visitVarInsn(ALOAD, 0);
            int local = 1;
            for (int i = 0; i < variables.size(); i++) {
                mv.visitVarInsn(variables.get(i).type.getOpcode(Opcodes.ILOAD), variables.get(i).var + 1);
                local = variables.get(i).var + 1 + variables.get(i).type.getSize();
            }
            mv.visitMethodInsn(INVOKESPECIAL, superNode.name, methodNode.name, methodNode.desc, false);
            mv.visitInsn(RETURN);
            mv.visitMaxs(local, local);
            mv.visitEnd();
        }
    }

    for (InstantMethod method : visitor.superMethods) {
        MethodVisitor mv = visitMethod(ACC_PUBLIC + ACC_STATIC, method.getName(), method.getDescriptor(), null,
                null);
        mv.visitCode();
        Type[] args = Type.getArgumentTypes(method.getDescriptor());

        List<LocalVariable> variables = ByteCodeUtils.toLocalVariables(Arrays.asList(args));
        int totSize = 1;
        for (LocalVariable variable : variables) {

            mv.visitVarInsn(variable.type.getOpcode(Opcodes.ILOAD), variable.var);
            totSize = variable.var;
        }

        mv.visitMethodInsn(INVOKESPECIAL, method.getOwner(), method.getName(), method.getOriDesc(), false);

        Type returnType = Type.getReturnType(method.getDescriptor());
        mv.visitInsn(returnType.getOpcode(Opcodes.IRETURN));
        mv.visitMaxs(totSize + 1, totSize + 1);
        mv.visitEnd();
    }

    visitEnd();
}

From source file:com.mto.asm.helloworld.ASMCodeGenerator.java

License:Open Source License

/**
 * Generate the byte code of a simple HelloWorld program
 *
 * public class HelloWorld/*from ww  w  .j a v a  2 s. c o  m*/
 * {
 *    public void sayHello()
 *    {
 *       System.out.println("Hello World");
 *    }
 * }
 * @return
 */
public byte[] generateHelloWorld() {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, "com/mto/asm/helloworld/HelloWorld", null, "java/lang/Object", null);

    cw.visitSource("HelloWorld.java", null);

    mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    Label l0 = new Label();
    mv.visitLabel(l0);
    mv.visitLineNumber(25, l0);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
    mv.visitInsn(RETURN);
    Label l1 = new Label();
    mv.visitLabel(l1);
    mv.visitLocalVariable("this", "Lcom/mto/asm/helloworld/HelloWorld;", null, l0, l1, 0);
    mv.visitMaxs(1, 1);
    mv.visitEnd();

    mv = cw.visitMethod(ACC_PUBLIC, "sayHello", "()V", null, null);
    mv.visitCode();
    l0 = new Label();
    mv.visitLabel(l0);
    mv.visitLineNumber(29, l0);
    mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
    mv.visitLdcInsn("Hello World");
    mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
    l1 = new Label();
    mv.visitLabel(l1);
    mv.visitLineNumber(30, l1);
    mv.visitInsn(RETURN);
    Label l2 = new Label();
    mv.visitLabel(l2);
    mv.visitLocalVariable("this", "Lcom/mto/asm/helloworld/HelloWorld;", null, l0, l2, 0);
    mv.visitMaxs(2, 1);
    mv.visitEnd();
    cw.visitEnd();

    return cw.toByteArray();
}

From source file:com.mulberry.athena.asm.ASMTest.java

License:Open Source License

@Test
public void generateClass() throws Exception {
    ClassWriter classWriter = new ClassWriter(0);
    ClassVisitor cv = new TraceClassVisitor(classWriter, new PrintWriter(System.out));
    //FieldVisitor fv;
    MethodVisitor mv;
    //AnnotationVisitor av0;

    cv.visit(V1_6, ACC_PUBLIC + ACC_SUPER, "Testing", null, "java/lang/Object", null);
    cv.visitSource("Testing.java", null);
    {//from   w w w .  jav a2 s  .co  m
        mv = cv.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(1, l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
        mv.visitInsn(RETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "LTesting;", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cv.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(3, l0);
        mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        mv.visitLdcInsn("Works!");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLineNumber(4, l1);
        mv.visitInsn(RETURN);
        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitLocalVariable("args", "[Ljava/lang/String;", null, l0, l2, 0);
        mv.visitMaxs(2, 1);
        mv.visitEnd();
    }
    cv.visitEnd();

    Class<?> clazz = new DynamicClassLoader().defineClass("Testing", classWriter.toByteArray());
    java.lang.reflect.Method method = clazz.getMethod("main", String[].class);
    final String[] arguments = new String[] { "hello", "world" };
    method.invoke(clazz, (Object) arguments);
}

From source file:com.nginious.http.serialize.JsonDeserializerCreator.java

License:Apache License

/**
 * Creates a JSON deserializer for the specified bean class unless a deserializer has already
 * been created. Created deserializers are cached and returned on subsequent calls to this method.
 * /* w ww  .j  av  a 2s .  c  o m*/
 * @param <T> class type for bean
 * @param beanClazz bean class for which a deserializer should be created
 * @return the created deserializer
 * @throws SerializerFactoryException if unable to create deserializer or class is not a bean
 */
@SuppressWarnings("unchecked")
protected <T> JsonDeserializer<T> create(Class<T> beanClazz) throws SerializerFactoryException {
    JsonDeserializer<T> deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz);

    if (deserializer != null) {
        return deserializer;
    }

    try {
        synchronized (this) {
            deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz);

            if (deserializer != null) {
                return deserializer;
            }

            checkDeserializability(beanClazz, "json");
            String intBeanClazzName = Serialization.createInternalClassName(beanClazz);
            Method[] methods = beanClazz.getMethods();

            String intDeserializerClazzName = new StringBuffer(intBeanClazzName).append("JsonDeserializer")
                    .toString();

            // Create class
            ClassWriter writer = new ClassWriter(0);
            String signature = Serialization
                    .createClassSignature("com/nginious/http/serialize/JsonDeserializer", intBeanClazzName);
            writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intDeserializerClazzName, signature,
                    "com/nginious/http/serialize/JsonDeserializer", null);

            // Create constructor
            Serialization.createConstructor(writer, "com/nginious/http/serialize/JsonDeserializer");

            // Create deserialize method
            MethodVisitor visitor = createDeserializeMethod(writer, intBeanClazzName);

            for (Method method : methods) {
                Serializable info = method.getAnnotation(Serializable.class);
                boolean canDeserialize = info == null
                        || (info != null && info.deserialize() && info.types().indexOf("json") > -1);

                if (canDeserialize && method.getName().startsWith("set")
                        && method.getReturnType().equals(void.class)
                        && method.getParameterTypes().length == 1) {
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    Class<?> parameterType = parameterTypes[0];

                    if (parameterType.isArray()) {
                        Class<?> arrayType = parameterType.getComponentType();

                        if (arrayType.equals(boolean.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeBooleanArray", "[Z", "[Z", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(double.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeDoubleArray", "[D", "[D", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(float.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeFloatArray", "[F", "[F", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(int.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeIntArray", "[I", "[I", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(long.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeLongArray", "[J", "[J", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(short.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeShortArray", "[S", "[S", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(String.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeStringArray", "[Ljava/lang/String;", "[Ljava/lang/String;",
                                    intBeanClazzName, method.getName());
                        }
                    } else if (parameterType.isPrimitive()) {
                        if (parameterType.equals(boolean.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeBoolean", "Z", "Z", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(double.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeDouble", "D", "D", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(float.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeFloat", "F", "F", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(int.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeInt", "I", "I", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(long.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeLong", "J", "J", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(short.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeShort", "S", "S", intBeanClazzName, method.getName());
                        }
                    } else if (parameterType.equals(Calendar.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                "deserializeCalendar", "Ljava/util/Calendar;", "Ljava/util/Calendar;",
                                intBeanClazzName, method.getName());
                    } else if (parameterType.equals(Date.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDate",
                                "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName());
                    } else if (parameterType.equals(String.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                "deserializeString", "Ljava/lang/String;", "Ljava/lang/String;",
                                intBeanClazzName, method.getName());
                    }
                }
            }

            visitor.visitVarInsn(Opcodes.ALOAD, 3);
            visitor.visitInsn(Opcodes.ARETURN);
            visitor.visitMaxs(5, 4);
            visitor.visitEnd();

            writer.visitEnd();
            byte[] clazzBytes = writer.toByteArray();
            ClassLoader controllerLoader = null;

            if (classLoader.hasLoaded(beanClazz)) {
                controllerLoader = beanClazz.getClassLoader();
            } else {
                controllerLoader = this.classLoader;
            }

            Class<?> clazz = Serialization.loadClass(controllerLoader,
                    intDeserializerClazzName.replace('/', '.'), clazzBytes);
            deserializer = (JsonDeserializer<T>) clazz.newInstance();
            deserializers.put(beanClazz, deserializer);
            return deserializer;
        }
    } catch (IllegalAccessException e) {
        throw new SerializerFactoryException(e);
    } catch (InstantiationException e) {
        throw new SerializerFactoryException(e);
    }
}

From source file:com.nginious.http.serialize.JsonSerializerCreator.java

License:Apache License

/**
 * Creates a JSON serializer for the specified bean class unless a serializer has already been
 * created. Created serializers are cached and returned on subsequent calls to this method.
 * //w  w w  .j  a  va 2 s .  c  om
 * @param factory serializer factory
 * @param <T> class type for bean
 * @param beanClazz bean class for which a serializer should be created
 * @return the created serializer
 * @throws SerializerFactoryException if unable to create serializer or class is not a bean
 */
@SuppressWarnings("unchecked")
<T> JsonSerializer<T> create(SerializerFactoryImpl factory, Class<T> beanClazz)
        throws SerializerFactoryException {
    JsonSerializer<T> serializer = (JsonSerializer<T>) serializers.get(beanClazz);

    if (serializer != null) {
        return serializer;
    }

    try {
        synchronized (this) {
            serializer = (JsonSerializer<T>) serializers.get(beanClazz);

            if (serializer != null) {
                return serializer;
            }

            checkSerializability(beanClazz, "json");
            String intBeanClazzName = Serialization.createInternalClassName(beanClazz);
            Method[] methods = beanClazz.getMethods();

            String intSerializerClazzName = new StringBuffer(intBeanClazzName).append("JsonSerializer")
                    .toString();

            // Create class
            ClassWriter writer = new ClassWriter(0);
            String signature = Serialization.createClassSignature("com/nginious/http/serialize/JsonSerializer",
                    intBeanClazzName);
            writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intSerializerClazzName, signature,
                    "com/nginious/http/serialize/JsonSerializer", null);

            // Create constructor
            Serialization.createConstructor(writer, "com/nginious/http/serialize/JsonSerializer");

            // Create serialize method
            MethodVisitor visitor = createSerializeMethod(writer, intBeanClazzName);

            for (Method method : methods) {
                Serializable info = method.getAnnotation(Serializable.class);
                boolean canSerialize = info == null
                        || (info != null && info.serialize() && info.types().indexOf("json") > -1);

                if (canSerialize && method.getName().startsWith("get") && !method.getName().equals("getClass")
                        && method.getReturnType() != null && method.getParameterTypes().length == 0) {
                    Class<?> returnType = method.getReturnType();
                    String propertyName = getPropertyName(method);

                    if (returnType.isPrimitive()) {
                        if (returnType.equals(boolean.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeBoolean",
                                    "Z", "Z", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(double.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDouble",
                                    "D", "D", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(float.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeFloat",
                                    "F", "F", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(int.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeInt",
                                    "I", "I", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(long.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeLong",
                                    "J", "J", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(short.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeShort",
                                    "S", "S", intBeanClazzName, method.getName(), propertyName);
                        }
                    } else if (Collection.class.isAssignableFrom(returnType)) {
                        Class<?> collectionType = canSerializeGenericCollectionType(method, "json");

                        if (collectionType != null) {
                            createBeanCollectionSerializationCode(visitor, intBeanClazzName, method.getName(),
                                    propertyName, returnType, collectionType);
                        } else {
                            createObjectCollectionSerializationCode(visitor, returnType, intBeanClazzName,
                                    method.getName(), propertyName);
                        }
                    } else if (returnType.equals(Calendar.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeCalendar",
                                "Ljava/util/Calendar;", "Ljava/util/Calendar;", intBeanClazzName,
                                method.getName(), propertyName);
                    } else if (returnType.equals(Date.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDate",
                                "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else if (returnType.equals(String.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeString",
                                "Ljava/lang/String;", "Ljava/lang/String;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else {
                        info = returnType.getAnnotation(Serializable.class);
                        canSerialize = info != null && info.serialize() && info.types().indexOf("json") > -1;

                        if (canSerialize) {
                            createBeanSerializationCode(visitor, method.getName(), propertyName, returnType,
                                    intBeanClazzName);
                        } else {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeObject",
                                    "Ljava/lang/Object;", "L" + returnType.getName().replace('.', '/') + ";",
                                    intBeanClazzName, method.getName(), propertyName);
                        }
                    }
                }
            }

            visitor.visitInsn(Opcodes.RETURN);
            visitor.visitMaxs(8, 7);
            visitor.visitEnd();

            writer.visitEnd();
            byte[] clazzBytes = writer.toByteArray();
            ClassLoader controllerLoader = null;

            if (classLoader.hasLoaded(beanClazz)) {
                controllerLoader = beanClazz.getClassLoader();
            } else {
                controllerLoader = this.classLoader;
            }

            Class<?> clazz = Serialization.loadClass(controllerLoader, intSerializerClazzName.replace('/', '.'),
                    clazzBytes);
            serializer = (JsonSerializer<T>) clazz.newInstance();
            String propertyName = Serialization.createPropertyNameFromClass(beanClazz);
            serializer.setName(propertyName);
            serializer.setType(beanClazz);
            serializer.setSerializerFactory(factory);
            serializers.put(beanClazz, serializer);
            return serializer;
        }
    } catch (IllegalAccessException e) {
        throw new SerializerFactoryException("Can't create JSON serializer for " + beanClazz.getName(), e);
    } catch (InstantiationException e) {
        throw new SerializerFactoryException("Can't create JSON serializer for " + beanClazz.getName(), e);
    }
}