Example usage for org.objectweb.asm MethodVisitor visitLocalVariable

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

Introduction

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

Prototype

public void visitLocalVariable(final String name, final String descriptor, final String signature,
        final Label start, final Label end, final int index) 

Source Link

Document

Visits a local variable declaration.

Usage

From source file:org.fabric3.monitor.impl.proxy.BytecodeMonitorProxyService.java

License:Open Source License

/**
 * Creates the writeParameters method. The method signature will take the same arguments as the proxy interface method that it is to be invoked from.
 *
 * @param cw         the class writer//from   w  w  w .j  a v a2  s  .com
 * @param index      the method index
 * @param signature  the parameter signature
 * @param paramTypes the parameter types
 */
private void writeGenerateParametersMethod(ClassWriter cw, int index, String signature, Class<?>[] paramTypes) {
    int varMethodArgOffset = 1;

    int offset = calculateParameterSpace(paramTypes);

    int varEntryPosition = offset + 1;
    int varNumberArgsPosition = varEntryPosition + 1;
    int varParamEntryPosition = varNumberArgsPosition + 1;
    int varIPosition = varParamEntryPosition + 1;

    MethodVisitor mv = cw.visitMethod(ACC_PRIVATE, "writeParameters" + index, signature, null, null);

    mv.visitCode();
    Label l0 = new Label();
    mv.visitLabel(l0);
    mv.visitLineNumber(103, l0);

    // set the number of arguments for this method
    pushInteger(paramTypes.length, mv);
    mv.visitVarInsn(ISTORE, varNumberArgsPosition);

    Label l1 = new Label();
    mv.visitLabel(l1);
    mv.visitLineNumber(104, l1);

    mv.visitVarInsn(ALOAD, varEntryPosition); //set the param entry limit
    mv.visitVarInsn(ILOAD, varNumberArgsPosition);
    mv.visitMethodInsn(INVOKEVIRTUAL, MONITOR_EVENT_ENTRY, "setLimit", "(I)V");

    Label l2 = new Label();
    mv.visitLabel(l2);
    mv.visitLineNumber(112, l2);

    // Setup i variable for the for loop and then iterate until the number of arguments is reached
    mv.visitInsn(ICONST_0);
    mv.visitVarInsn(ISTORE, varIPosition);

    Label l3 = new Label();
    mv.visitLabel(l3);

    // jump if i (specified by the for loop) is greater than the number of arguments
    mv.visitVarInsn(ILOAD, varIPosition);
    mv.visitVarInsn(ILOAD, varNumberArgsPosition);
    Label l4 = new Label();
    mv.visitJumpInsn(IF_ICMPGE, l4);

    Label endIf = new Label();
    for (int i = 0; i < paramTypes.length; i++) {
        // load ring buffer entry
        mv.visitVarInsn(ALOAD, varEntryPosition);
        mv.visitMethodInsn(INVOKEVIRTUAL, MONITOR_EVENT_ENTRY, "getEntries", "()[L" + PARAM_ENTRY + ";");
        pushInteger(i, mv);
        mv.visitInsn(AALOAD);
        mv.visitVarInsn(ASTORE, varParamEntryPosition);
        mv.visitVarInsn(ALOAD, varParamEntryPosition);

        Class<?> paramType = paramTypes[i];
        if (Character.TYPE.equals(paramType)) {
            // load method parameter
            mv.visitVarInsn(ILOAD, varMethodArgOffset + i);
            mv.visitMethodInsn(INVOKEVIRTUAL, PARAM_ENTRY, "setCharValue", "(C)V");
        } else if (Integer.TYPE.equals(paramType)) {
            mv.visitVarInsn(ILOAD, varMethodArgOffset + i);
            mv.visitMethodInsn(INVOKEVIRTUAL, PARAM_ENTRY, "setIntValue", "(I)V");
        } else if (Long.TYPE.equals(paramType)) {
            mv.visitVarInsn(LLOAD, varMethodArgOffset + i);
            mv.visitMethodInsn(INVOKEVIRTUAL, PARAM_ENTRY, "setLongValue", "(J)V");
        } else if (Double.TYPE.equals(paramType)) {
            mv.visitVarInsn(DLOAD, varMethodArgOffset + i);
            mv.visitMethodInsn(INVOKEVIRTUAL, PARAM_ENTRY, "setDoubleValue", "(D)V");
        } else if (Boolean.TYPE.equals(paramType)) {
            mv.visitVarInsn(ILOAD, varMethodArgOffset + i);
            mv.visitMethodInsn(INVOKEVIRTUAL, PARAM_ENTRY, "setBooleanValue", "(Z)V");
        } else if (Float.TYPE.equals(paramType)) {
            mv.visitVarInsn(FLOAD, varMethodArgOffset + i);
            mv.visitMethodInsn(INVOKEVIRTUAL, PARAM_ENTRY, "setFloatValue", "(F)V");
        } else if (Short.TYPE.equals(paramType)) {
            mv.visitVarInsn(ILOAD, varMethodArgOffset + i);
            mv.visitMethodInsn(INVOKEVIRTUAL, PARAM_ENTRY, "setShortValue", "(S)V");
        } else if (Byte.TYPE.equals(paramType)) {
            mv.visitVarInsn(ILOAD, varMethodArgOffset + i);
            mv.visitMethodInsn(INVOKEVIRTUAL, PARAM_ENTRY, "setByteValue", "(B)V");
        } else if (Object.class.isAssignableFrom(paramType)) {
            mv.visitVarInsn(ALOAD, varMethodArgOffset + i);
            mv.visitMethodInsn(INVOKEVIRTUAL, PARAM_ENTRY, "setObjectValue", "(Ljava/lang/Object;)V");
        } else {
            throw new AssertionError("Unhandled type: " + paramType);
        }
    }
    mv.visitLabel(endIf);
    mv.visitLineNumber(121, endIf);

    // increment i and counter, then loop
    mv.visitIincInsn(varIPosition, 1);
    mv.visitJumpInsn(GOTO, l3);
    // end of for loop

    mv.visitLabel(l4);

    mv.visitInsn(RETURN);
    Label endMethod = new Label();
    mv.visitLabel(endMethod);

    mv.visitLocalVariable("this", "L" + ABSTRACT_MONITOR_HANDLER + ";", null, l0, endMethod, 0);

    for (int i = 1; i <= paramTypes.length; i++) {
        Class<?> paramType = paramTypes[i - 1];
        if (Integer.TYPE.equals(paramType)) {
            mv.visitLocalVariable("arg" + i, "I", null, l0, endMethod, i + 1);
        } else if (Long.TYPE.equals(paramType)) {
            mv.visitLocalVariable("arg" + i, "J", null, l0, endMethod, i + 1);
        } else if (Double.TYPE.equals(paramType)) {
            mv.visitLocalVariable("arg" + i, "D", null, l0, endMethod, i + 1);
        } else if (Boolean.TYPE.equals(paramType)) {
            mv.visitLocalVariable("arg" + i, "Z", null, l0, endMethod, i + 1);
        } else if (Float.TYPE.equals(paramType)) {
            mv.visitLocalVariable("arg" + i, "F", null, l0, endMethod, i + 1);
        } else if (Short.TYPE.equals(paramType)) {
            mv.visitLocalVariable("arg" + i, "S", null, l0, endMethod, i + 1);
        } else if (Byte.TYPE.equals(paramType)) {
            mv.visitLocalVariable("arg" + i, "B", null, l0, endMethod, i + 1);
        } else if (Character.TYPE.equals(paramType)) {
            mv.visitLocalVariable("arg" + i, "C", null, l0, endMethod, i + 1);
        } else if (paramType.isPrimitive()) {
            throw new AssertionError("Unhandled type");
        } else {
            mv.visitLocalVariable("arg" + i, "Ljava/lang/Object;", null, l0, endMethod, i + 1);
        }
    }

    mv.visitLocalVariable("entry", "L" + MONITOR_EVENT_ENTRY + ";", null, l0, endMethod, varEntryPosition);
    mv.visitLocalVariable("numberArgs", "I", null, l1, endMethod, varNumberArgsPosition);
    mv.visitLocalVariable("current", "L" + PARAM_ENTRY + ";", null, l2, endMethod, varParamEntryPosition);
    mv.visitLocalVariable("i", "I", null, l2, endMethod, varIPosition);

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

}

From source file:org.fabric3.monitor.impl.proxy.BytecodeMonitorProxyService.java

License:Open Source License

private void writeConstructor(ClassWriter cw, String proxyClassDescriptor) {
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();// ww  w  .  j  a  v a 2 s .com
    Label l0 = new Label();
    mv.visitLabel(l0);
    mv.visitLineNumber(56, l0);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, ABSTRACT_MONITOR_HANDLER, "<init>", "()V");
    mv.visitInsn(RETURN);
    Label l1 = new Label();
    mv.visitLabel(l1);
    mv.visitLocalVariable("this", proxyClassDescriptor, null, l0, l1, 0);
    mv.visitMaxs(1, 1);
    mv.visitEnd();
}

From source file:org.forgerock.openidm.shell.felixgogo.FelixGogoCommandsServiceGenerator.java

License:Apache License

/**
 * Generate CommandProvider class and newBuilder for this class based on parameters.
 *
 * @param service  commands service// w  w  w.  jav  a2s  .c  o  m
 * @param commands commands map (name=help)
 * @param suffix   unique class suffix
 * @return generated CommandProvider newBuilder
 * @throws Exception if something went wrong
 */
public static Object generate(CustomCommandScope service, Map<String, String> commands, String suffix)
        throws Exception {
    // generate class with unique name
    //javassist.CtClass ctClass = POOL.makeClass(AbstractFelixCommandsService.class.getName() + suffix);

    try {
        ClassWriter cw = new ClassWriter(0);
        MethodVisitor mv;
        AnnotationVisitor av0;
        String className = AbstractFelixCommandsService.class.getName().replace('.', '/') + suffix;
        cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, className, null,
                AbstractFelixCommandsService.class.getName().replace('.', '/'), null);

        //cw.visitSource("AbstractFelixCommandsServiceSample.java", null);

        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "(Ljava/lang/Object;)V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(10, l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitMethodInsn(INVOKESPECIAL, AbstractFelixCommandsService.class.getName().replace('.', '/'),
                "<init>", "(Ljava/lang/Object;)V");
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLineNumber(11, l1);
        mv.visitInsn(RETURN);
        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitLocalVariable("this", "L" + className + ";", null, l0, l2, 0);
        mv.visitLocalVariable("service", "Ljava/lang/Object;", null, l0, l2, 1);
        mv.visitMaxs(2, 2);
        mv.visitEnd();

        /*javassist.bytecode.ClassFile ccFile = ctClass.getClassFile();
        ccFile.setVersionToJava5();
        javassist.bytecode.ConstPool constPool = ccFile.getConstPool();
                
        // set superclass
        javassist.CtClass abstractCtClass = POOL.getCtClass(AbstractFelixCommandsService.class.getName());
        ctClass.setSuperclass(abstractCtClass);
                
        // add constructor
        javassist.CtClass serviceCtClass = POOL.getCtClass(Object.class.getName());
        javassist.CtConstructor ctConstructor = new javassist.CtConstructor(new javassist.CtClass[]{serviceCtClass},
            ctClass);
        ctConstructor.setModifiers(javassist.Modifier.PUBLIC);
        ctConstructor.setBody("super($1);");
        ctClass.addConstructor(ctConstructor);
                
        // add method for each command
        javassist.CtClass sessionCtClass = POOL.getCtClass(CommandSession.class.getName());
        javassist.CtClass stringArrayCtClass = POOL.getCtClass(String[].class.getName());*/
        Set<String> names = commands.keySet();
        for (String name : names) {
            if (isMethodAvailable(service, name)) {
                mv = cw.visitMethod(ACC_PUBLIC, name,
                        "(Lorg/apache/felix/service/command/CommandSession;[Ljava/lang/String;)V", null, null);

                av0 = mv.visitAnnotation("Lorg/apache/felix/service/command/Descriptor;", true);
                av0.visit("value", commands.get(name));
                av0.visitEnd();

                mv.visitCode();
                l0 = new Label();
                mv.visitLabel(l0);
                mv.visitLineNumber(15, l0);
                mv.visitVarInsn(ALOAD, 0);
                mv.visitLdcInsn(name);
                mv.visitVarInsn(ALOAD, 1);
                mv.visitVarInsn(ALOAD, 2);
                mv.visitMethodInsn(INVOKEVIRTUAL, className, "runCommand",
                        "(Ljava/lang/String;Lorg/apache/felix/service/command/CommandSession;"
                                + "[Ljava/lang/String;)V");
                l1 = new Label();
                mv.visitLabel(l1);
                mv.visitLineNumber(16, l1);
                mv.visitInsn(RETURN);
                l2 = new Label();
                mv.visitLabel(l2);
                mv.visitLocalVariable("this", "L" + className + ";", null, l0, l2, 0);
                mv.visitLocalVariable("session", "Lorg/apache/felix/service/command/CommandSession;", null, l0,
                        l2, 1);
                mv.visitLocalVariable("args", "[Ljava/lang/String;", null, l0, l2, 2);
                mv.visitMaxs(4, 3);
                mv.visitEnd();

                /*javassist.CtMethod ctMethod = new javassist.CtMethod(javassist.CtClass.voidType, name,
                    new javassist.CtClass[]{
                        sessionCtClass, stringArrayCtClass
                    }, ctClass);
                ctMethod.setModifiers(javassist.Modifier.PUBLIC);
                ctMethod.setBody("runCommand(\"" + name + "\", $1, $2);");
                ctClass.addMethod(ctMethod);
                        
                // add GoGo descriptor for this shell command
                javassist.bytecode.AnnotationsAttribute annotationsAttribute =
                    new javassist.bytecode.AnnotationsAttribute(constPool,
                        javassist.bytecode.AnnotationsAttribute.visibleTag);
                javassist.bytecode.annotation.Annotation annotation =
                    new javassist.bytecode.annotation.Annotation(Descriptor.class.getName(), constPool);
                annotation.addMemberValue("value",
                    new javassist.bytecode.annotation.StringMemberValue(commands.get(name), constPool));
                annotationsAttribute.addAnnotation(annotation);
                ctMethod.getMethodInfo().addAttribute(annotationsAttribute);*/
            }
        }

        cw.visitEnd();
        // create new newBuilder
        /*Class<?> aClass = ctClass.toClass(FelixGogoCommandsServiceGenerator.class.getClassLoader(), null);
        */
        Class<?> aClass = classLoader.defineClass(className, cw.toByteArray());
        Constructor<?> constructor = aClass.getConstructor(Object.class);
        return constructor.newInstance(service);
    } catch (Exception e) {
        //ctClass.detach();
        throw e;
    }
}

From source file:org.jboss.errai.BoringClassGenerator.java

License:Apache License

/**
 * Generates a class with a no-args public constructor.
 *
 * @param loader//from w  w w  .  j ava  2s. c  o m
 *          ignored.
 * @param className
 *          The generated class has this package and name.
 * @param classBeingRedefined
 *          ignored.
 * @param protectionDomain
 *          ignored.
 * @param classfileBuffer
 *          ignored.
 * @return bytecode for an empty class whose package and class name are
 *         determined by the {@code className} parameter.
 */
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

    if (!hiddenClassNamePattern.matcher(className).matches()) {
        if (debug) {
            System.out.println("client-local-class-hider: not hiding " + className);
        }
        return null;
    }

    if (debug) {
        System.out.println("client-local-class-hider: hiding " + className);
    }

    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, className, null, "java/lang/Object", null);

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

    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(15, 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", "L" + className + ";", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }

    cw.visitEnd();

    return cw.toByteArray();
}

From source file:org.jboss.errai.EmtpyClassGenerator.java

License:Apache License

/**
 * Generate an empty class: a trivial public subclass of java.lang.Object
 * which is in the expected package and has the expected name.
 * /*from   w  w  w .j a  v  a 2  s. com*/
 * @param className
 *          the fully qualified class name
 * @return byte array representing the empty class
 */
public static byte[] generateEmptyClass(String className) {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, className, null, "java/lang/Object", null);

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

    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(15, 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", "L" + className + ";", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }

    cw.visitEnd();

    return cw.toByteArray();
}

From source file:org.kantega.notsoserial.ReadObjectClassVisitor.java

License:Apache License

@Override
public void visitEnd() {
    if (!isInterface() && isSerializable() && !hasReadObject) {

        MethodVisitor mv = super.visitMethod(Opcodes.ACC_PRIVATE, "readObject", readObjectDescription, null,
                readObjectExceptions);//from  w ww  .j a v a  2 s  .  c  om
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLdcInsn(className);
        mv.visitMethodInsn(Opcodes.INVOKESTATIC,
                Type.getType(NotSoSerialClassFileTransformer.class).getInternalName(),
                onReadObjectCallbackMethod, "(Ljava/lang/String;)V", false);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/ObjectInputStream", "defaultReadObject", "()V",
                false);
        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitInsn(Opcodes.RETURN);
        Label l3 = new Label();
        mv.visitLabel(l3);
        mv.visitLocalVariable("this", Type.getObjectType(className).getDescriptor(), classSignature, l0, l3, 0);
        mv.visitLocalVariable("stream", Type.getType(ObjectInputStream.class).getDescriptor(), null, l0, l3, 1);
        mv.visitMaxs(1, 2);
        mv.visitEnd();

    }
    super.visitEnd();
}

From source file:org.kantega.revoc.demo.HelloWorldGenerator.java

License:Apache License

public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException,
        InvocationTargetException, IllegalAccessException {

    ClassWriter cw = new ClassWriter(0);

    cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, "org/kantega/revoc/instrumentation/HelloWorld", null,
            "java/lang/Object", null);

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

    {//from   w  ww .j av  a2  s  .  c o m
        MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null,
                null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(9, 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");
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLineNumber(10, 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();
    }
    cw.visitEnd();

    byte[] bytes = cw.toByteArray();

    ClassUtils.invokeMainMethodUsingReflection("org.kantega.helloworld.HelloWorld", bytes);
}

From source file:org.kjots.json.object.JsonObjectGeneratorBase.java

License:Apache License

/**
 * Generate the constructor./*from w w w. ja va  2s  .  c  o  m*/
 *
 * @param classVisitor The class visitor.
 * @param jsonObjectImplType The type of the JSON object implementation.
 * @param superJsonObjectImplType The type of the super JSON object implementation.
 */
private void generateConstructor(ClassVisitor classVisitor, Type jsonObjectImplType,
        Type superJsonObjectImplType) {
    Method constructor = Method.getMethod(this.getJsonObjectImplConstructor());
    Type[] argumentTypes = constructor.getArgumentTypes();

    int maxLocals = 1;

    MethodVisitor methodVisitor = classVisitor.visitMethod(ACC_PUBLIC, constructor, null, null);

    Label start = new Label();
    Label end = new Label();

    methodVisitor.visitCode();

    methodVisitor.visitLabel(start);
    methodVisitor.visitVarInsn(ALOAD, 0);
    for (int i = 0, index = 1; i < argumentTypes.length; i++) {
        Type argumentType = argumentTypes[i];

        methodVisitor.visitVarInsn(argumentType.getOpcode(ILOAD), index);

        index += argumentType.getSize();
    }
    methodVisitor.visitMethodInsn(INVOKESPECIAL, superJsonObjectImplType, constructor);
    methodVisitor.visitInsn(RETURN);
    methodVisitor.visitLabel(end);

    methodVisitor.visitLocalVariable("this", jsonObjectImplType, null, start, end, 0);
    for (int i = 0; i < argumentTypes.length; i++) {
        Type argumentType = argumentTypes[i];

        methodVisitor.visitLocalVariable("arg" + i, argumentType, null, start, end, maxLocals);

        maxLocals += argumentType.getSize();
    }
    methodVisitor.visitMaxs(maxLocals, maxLocals);

    methodVisitor.visitEnd();
}

From source file:org.kjots.json.object.JsonObjectGeneratorBase.java

License:Apache License

/**
 * Generate a function method./*  www .j a  v  a2 s. co m*/
 *
 * @param classVisitor The class visitor.
 * @param jsonObjectImplType The type of the JSON object implementation.
 * @param jsonObjectClass The class of the JSON object.
 * @param method The method.
 * @param jsonFunctionAnnotation The JSON function annotation.
 * @param varargs The variable arguments flag.
 */
private void generateFunctionMethod(ClassVisitor classVisitor, Type jsonObjectImplType,
        Class<? extends JsonObject> jsonObjectClass, Method method, JsonFunction jsonFunctionAnnotation,
        boolean varargs) {
    Type returnType = method.getReturnType();
    Type[] argumentTypes = method.getArgumentTypes();

    int maxLocals = 1;

    MethodVisitor methodVisitor = classVisitor.visitMethod(ACC_PUBLIC + ACC_FINAL + (varargs ? ACC_VARARGS : 0),
            method, null, null);

    Label start = new Label();
    Label end = new Label();

    methodVisitor.visitCode();

    methodVisitor.visitLabel(start);
    methodVisitor.visitVarInsn(ALOAD, 0);
    for (int i = 0, index = 1; i < argumentTypes.length; i++) {
        Type argumentType = argumentTypes[i];

        methodVisitor.visitVarInsn(argumentType.getOpcode(ILOAD), index);

        index += argumentType.getSize();
    }
    methodVisitor.visitMethodInsn(INVOKESTATIC, Type.getType(jsonFunctionAnnotation.klass()),
            this.getJsonFunctionMethod(jsonObjectClass, method, jsonFunctionAnnotation));
    methodVisitor.visitInsn(returnType.getOpcode(IRETURN));
    methodVisitor.visitLabel(end);

    methodVisitor.visitLocalVariable("this", jsonObjectImplType, null, start, end, 0);
    for (int i = 0; i < argumentTypes.length; i++) {
        Type argumentType = argumentTypes[i];

        methodVisitor.visitLocalVariable("arg" + i, argumentType, null, start, end, maxLocals);

        maxLocals += argumentType.getSize();
    }
    methodVisitor.visitMaxs(Math.max(maxLocals, returnType.getSize()), maxLocals);

    methodVisitor.visitEnd();
}

From source file:org.kjots.json.object.JsonObjectGeneratorBase.java

License:Apache License

/**
 * Generate an exception method.//from  w  w w.  ja v a2s  .c  o  m
 *
 * @param classVisitor The class visitor.
 * @param jsonObjectImplType The type of the JSON object implementation.
 * @param jsonObjectClass The class of the JSON object.
 * @param method The method.
 * @param jsonExceptionAnnotation The JSON exception annotation.
 * @param varargs The variable arguments flag.
 */
private void generateExceptionMethod(ClassVisitor classVisitor, Type jsonObjectImplType,
        Class<? extends JsonObject> jsonObjectClass, Method method, JsonException jsonExceptionAnnotation,
        boolean varargs) {
    Type[] argumentTypes = method.getArgumentTypes();
    Type exceptionType = Type.getType(jsonExceptionAnnotation.klass());
    String message = jsonExceptionAnnotation.message();

    int maxLocals = 1;

    MethodVisitor methodVisitor = classVisitor.visitMethod(ACC_PUBLIC + ACC_FINAL + (varargs ? ACC_VARARGS : 0),
            method, null, null);

    Label start = new Label();
    Label end = new Label();

    methodVisitor.visitCode();

    methodVisitor.visitLabel(start);
    methodVisitor.visitTypeInsn(NEW, exceptionType);
    methodVisitor.visitInsn(DUP);
    if (message.isEmpty()) {
        methodVisitor.visitMethodInsn(INVOKESPECIAL, exceptionType, getConstructor());
    } else {
        methodVisitor.visitLdcInsn(message);
        methodVisitor.visitMethodInsn(INVOKESPECIAL, exceptionType, getConstructor(Type.getType(String.class)));
    }
    methodVisitor.visitInsn(ATHROW);
    methodVisitor.visitLabel(end);

    methodVisitor.visitLocalVariable("this", jsonObjectImplType, null, start, end, 0);
    for (int i = 0; i < argumentTypes.length; i++) {
        Type argumentType = argumentTypes[i];

        methodVisitor.visitLocalVariable("arg" + i, argumentType, null, start, end, maxLocals);

        maxLocals += argumentType.getSize();
    }
    methodVisitor.visitMaxs(message.isEmpty() ? 2 : 3, maxLocals);

    methodVisitor.visitEnd();
}