Example usage for org.objectweb.asm.commons Method getMethod

List of usage examples for org.objectweb.asm.commons Method getMethod

Introduction

In this page you can find the example usage for org.objectweb.asm.commons Method getMethod.

Prototype

public static Method getMethod(final String method) 

Source Link

Document

Returns a Method corresponding to the given Java method declaration.

Usage

From source file:org.apache.deltaspike.proxy.impl.AsmProxyClassGenerator.java

License:Apache License

private static void defineDeltaSpikeProxyMethods(ClassWriter cw, Type proxyType,
        Type delegateInvocationHandlerType) {
    try {/* w  ww .  jav a 2 s. com*/
        // implement #setDelegateInvocationHandler
        Method asmMethod = Method.getMethod(DeltaSpikeProxy.class
                .getDeclaredMethod("setDelegateInvocationHandler", InvocationHandler.class));
        GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, asmMethod, null, null, cw);

        mg.visitCode();

        mg.loadThis();
        mg.loadArg(0);
        mg.checkCast(delegateInvocationHandlerType);
        mg.putField(proxyType, FIELDNAME_DELEGATE_INVOCATION_HANDLER, delegateInvocationHandlerType);
        mg.returnValue();

        mg.visitMaxs(2, 1);
        mg.visitEnd();

        // implement #getDelegateInvocationHandler
        asmMethod = Method.getMethod(DeltaSpikeProxy.class.getDeclaredMethod("getDelegateInvocationHandler"));
        mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, asmMethod, null, null, cw);

        mg.visitCode();

        mg.loadThis();
        mg.getField(proxyType, FIELDNAME_DELEGATE_INVOCATION_HANDLER, delegateInvocationHandlerType);
        mg.returnValue();

        mg.visitMaxs(2, 1);
        mg.visitEnd();
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException("Unable to implement " + DeltaSpikeProxy.class.getName(), e);
    }
}

From source file:org.apache.deltaspike.proxy.impl.AsmProxyClassGenerator.java

License:Apache License

private static void defineMethod(ClassWriter cw, java.lang.reflect.Method method,
        Class manualInvocationHandlerClass) {
    Type methodType = Type.getType(method);

    ArrayList<Type> exceptionsToCatch = new ArrayList<Type>();
    for (Class<?> exception : method.getExceptionTypes()) {
        if (!RuntimeException.class.isAssignableFrom(exception)) {
            exceptionsToCatch.add(Type.getType(exception));
        }/*w w  w  .j av  a 2 s  .co  m*/
    }

    // push the method definition
    int modifiers = (Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED) & method.getModifiers();
    Method asmMethod = Method.getMethod(method);
    GeneratorAdapter mg = new GeneratorAdapter(modifiers, asmMethod, null, getTypes(method.getExceptionTypes()),
            cw);

    // copy annotations
    for (Annotation annotation : method.getDeclaredAnnotations()) {
        mg.visitAnnotation(Type.getDescriptor(annotation.annotationType()), true).visitEnd();
    }

    mg.visitCode();

    Label tryBlockStart = mg.mark();

    mg.loadThis();
    loadCurrentMethod(mg, method, methodType);
    loadArguments(mg, method, methodType);

    // invoke our ProxyInvocationHandler
    mg.invokeStatic(Type.getType(manualInvocationHandlerClass),
            Method.getMethod("Object staticInvoke(Object, java.lang.reflect.Method, Object[])"));

    // cast the result
    mg.unbox(methodType.getReturnType());

    // build try catch
    Label tryBlockEnd = mg.mark();

    // push return
    mg.returnValue();

    // catch runtime exceptions and rethrow it
    Label rethrow = mg.mark();
    mg.visitVarInsn(Opcodes.ASTORE, 1);
    mg.visitVarInsn(Opcodes.ALOAD, 1);
    mg.throwException();
    mg.visitTryCatchBlock(tryBlockStart, tryBlockEnd, rethrow, Type.getInternalName(RuntimeException.class));

    // catch checked exceptions and rethrow it
    boolean throwableCatched = false;
    if (exceptionsToCatch.size() > 0) {
        rethrow = mg.mark();
        mg.visitVarInsn(Opcodes.ASTORE, 1);
        mg.visitVarInsn(Opcodes.ALOAD, 1);
        mg.throwException();

        // catch declared exceptions and rethrow it...
        for (Type exceptionType : exceptionsToCatch) {
            if (exceptionType.getClassName().equals(Throwable.class.getName())) {
                throwableCatched = true;
            }
            mg.visitTryCatchBlock(tryBlockStart, tryBlockEnd, rethrow, exceptionType.getInternalName());
        }
    }

    // if throwable isn't alreached cachted, catch it and wrap it with an UndeclaredThrowableException and throw it
    if (!throwableCatched) {
        Type uteType = Type.getType(UndeclaredThrowableException.class);
        Label wrapAndRethrow = mg.mark();

        mg.visitVarInsn(Opcodes.ASTORE, 1);
        mg.newInstance(uteType);
        mg.dup();
        mg.visitVarInsn(Opcodes.ALOAD, 1);
        mg.invokeConstructor(uteType, Method.getMethod("void <init>(java.lang.Throwable)"));
        mg.throwException();

        mg.visitTryCatchBlock(tryBlockStart, tryBlockEnd, wrapAndRethrow,
                Type.getInternalName(Throwable.class));
    }

    // finish the method
    mg.endMethod();
    mg.visitMaxs(10, 10);
    mg.visitEnd();
}

From source file:org.apache.deltaspike.proxy.util.AsmProxyClassGenerator.java

License:Apache License

private static void defineDelegateInvocationHandlerConstructor(ClassWriter cw, Type proxyType, Type superType,
        Type invocationHandlerType) {
    GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC,
            new Method("<init>", Type.VOID_TYPE, new Type[] { invocationHandlerType }), null, null, cw);

    mg.visitCode();// w ww.  j  av  a 2  s.c om

    // invoke super constructor
    mg.loadThis();
    mg.invokeConstructor(superType, Method.getMethod("void <init> ()"));

    // set invocation handler
    mg.loadThis();
    mg.loadArg(0);
    mg.putField(proxyType, FIELDNAME_DELEGATE_INVOCATION_HANDLER, invocationHandlerType);

    mg.returnValue();
    mg.endMethod();

    mg.visitEnd();
}

From source file:org.apache.deltaspike.proxy.util.AsmProxyClassGenerator.java

License:Apache License

private static void defineDeltaSpikeProxyMethods(ClassWriter cw, Type proxyType, Type invocationHandlerType) {
    try {/*w  w w  . ja va  2  s.  c  om*/
        // implement #setDelegateInvocationHandler
        Method asmMethod = Method.getMethod(DeltaSpikeProxy.class
                .getDeclaredMethod("setDelegateInvocationHandler", InvocationHandler.class));
        GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, asmMethod, null, null, cw);

        mg.visitCode();

        mg.loadThis();
        mg.loadArg(0);
        mg.checkCast(invocationHandlerType);
        mg.putField(proxyType, FIELDNAME_DELEGATE_INVOCATION_HANDLER, invocationHandlerType);
        mg.returnValue();

        mg.visitMaxs(2, 1);
        mg.visitEnd();

        // implement #getDelegateInvocationHandler
        asmMethod = Method.getMethod(DeltaSpikeProxy.class.getDeclaredMethod("getDelegateInvocationHandler"));
        mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, asmMethod, null, null, cw);

        mg.visitCode();

        mg.loadThis();
        mg.getField(proxyType, FIELDNAME_DELEGATE_INVOCATION_HANDLER, invocationHandlerType);
        mg.returnValue();

        mg.visitMaxs(2, 1);
        mg.visitEnd();
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException("Unable to implement " + DeltaSpikeProxy.class.getName(), e);
    }
}

From source file:org.elasticsearch.painless.node.EListInit.java

License:Apache License

@Override
void write(MethodWriter writer, Globals globals) {
    writer.writeDebugInfo(location);/*from  ww w  . ja v  a2s . c o m*/

    writer.newInstance(MethodWriter.getType(actual));
    writer.dup();
    writer.invokeConstructor(Type.getType(constructor.javaConstructor.getDeclaringClass()),
            Method.getMethod(constructor.javaConstructor));

    for (AExpression value : values) {
        writer.dup();
        value.write(writer, globals);
        writer.invokeMethodCall(method);
        writer.pop();
    }
}

From source file:org.elasticsearch.painless.node.EMapInit.java

License:Apache License

@Override
void write(MethodWriter writer, Globals globals) {
    writer.writeDebugInfo(location);/*from w  w  w .  j ava 2s . co m*/

    writer.newInstance(MethodWriter.getType(actual));
    writer.dup();
    writer.invokeConstructor(Type.getType(constructor.javaConstructor.getDeclaringClass()),
            Method.getMethod(constructor.javaConstructor));

    for (int index = 0; index < keys.size(); ++index) {
        AExpression key = keys.get(index);
        AExpression value = values.get(index);

        writer.dup();
        key.write(writer, globals);
        value.write(writer, globals);
        writer.invokeMethodCall(method);
        writer.pop();
    }
}

From source file:org.elasticsearch.painless.node.ENewObj.java

License:Apache License

@Override
void write(MethodWriter writer, Globals globals) {
    writer.writeDebugInfo(location);/* ww w  .j  a  v  a2s  . c  o m*/

    writer.newInstance(MethodWriter.getType(actual));

    if (read) {
        writer.dup();
    }

    for (AExpression argument : arguments) {
        argument.write(writer, globals);
    }

    writer.invokeConstructor(Type.getType(constructor.javaConstructor.getDeclaringClass()),
            Method.getMethod(constructor.javaConstructor));
}

From source file:org.evosuite.instrumentation.MethodCallReplacementClassAdapter.java

License:Open Source License

@Override
public void visitEnd() {
    if (!definesHashCode && !isInterface && Properties.REPLACE_CALLS) {
        logger.info("No hashCode defined for: {}, superclass = {}", className, superClassName);
        if (superClassName.equals("java.lang.Object")) {
            Method hashCodeMethod = Method.getMethod("int hashCode()");
            GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, hashCodeMethod, null, null, this);
            mg.loadThis();/*from   ww w.j av  a 2 s .com*/
            mg.visitAnnotation("Lorg/evosuite/annotation/EvoSuiteExclude;", true);
            mg.invokeStatic(Type.getType(org.evosuite.runtime.System.class),
                    Method.getMethod("int identityHashCode(Object)"));
            mg.returnValue();
            mg.endMethod();

            /*
             * If the class is serializable, then adding a hashCode will change the serialVersionUID
             * if it is not defined in the class. Hence, if it is not defined, we have to define it to
             * avoid problems in serialising the class.
             */
            /*
            if(!definesUid) {
               try {
                  Class<?> clazz = Class.forName(className.replace('/', '.'), false, MethodCallReplacementClassAdapter.class.getClassLoader());
                  if(Serializable.class.isAssignableFrom(clazz)) {
                  ObjectStreamClass c = ObjectStreamClass.lookup(clazz);
                  long serialID = c.getSerialVersionUID();
                  logger.info("Adding serialId to class "+className);
                  visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, "serialVersionUID", "J", null, serialID);
                  }
               } catch(ClassNotFoundException e) {
                  logger.info("Failed to add serialId to class "+className+": "+e.getMessage());
               }
            */
        }
    }
    super.visitEnd();
}

From source file:org.evosuite.junit.TestSuiteWriter.java

License:Open Source License

/**
 * Get bytecode representation of test class
 * //from   w ww.  j a va2 s  .c  o  m
 * @param name
 *            a {@link java.lang.String} object.
 * @return an array of byte.
 */
public byte[] getBytecode(String name) {
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String prefix = Properties.TARGET_CLASS.substring(0, Properties.TARGET_CLASS.lastIndexOf(".")).replace(".",
            "/");
    cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, prefix + "/" + name, null, "junit/framework/TestCase", null);

    Method m = Method.getMethod("void <init> ()");
    GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cw);
    mg.loadThis();
    mg.invokeConstructor(Type.getType(junit.framework.TestCase.class), m);
    mg.returnValue();
    mg.endMethod();

    int num = 0;
    for (TestCase test : testCases) {
        ExecutionResult result = runTest(test);
        m = Method.getMethod("void test" + num + " ()");
        mg = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cw);
        testToBytecode(test, mg, result.exposeExceptionMapping());
        num++;
    }

    // main method
    m = Method.getMethod("void main (String[])");
    mg = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, m, null, null, cw);
    mg.push(1);
    mg.newArray(Type.getType(String.class));
    mg.dup();
    mg.push(0);
    mg.push(Properties.CLASS_PREFIX + "." + name);
    mg.arrayStore(Type.getType(String.class));
    // mg.invokeStatic(Type.getType(org.junit.runner.JUnitCore.class),
    // Method.getMethod("void main (String[])"));
    mg.invokeStatic(Type.getType(junit.textui.TestRunner.class), Method.getMethod("void main (String[])"));
    mg.returnValue();
    mg.endMethod();

    cw.visitEnd();
    return cw.toByteArray();
}

From source file:org.evosuite.runtime.instrumentation.MethodCallReplacementClassAdapter.java

License:Open Source License

@Override
public void visitEnd() {
    if (canChangeSignature && !definesHashCode && !isInterface && RuntimeSettings.mockJVMNonDeterminism) {

        logger.info("No hashCode defined for: " + className + ", superclass = " + superClassName);

        if (superClassName.equals("java.lang.Object")) { //TODO: why only if superclass is Object??? unclear
            Method hashCodeMethod = Method.getMethod("int hashCode()");
            GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, hashCodeMethod, null, null, this);
            mg.loadThis();/*from w  ww  .  j  a va 2  s .  c o m*/
            mg.visitAnnotation(Type.getDescriptor(EvoSuiteExclude.class), true);
            mg.invokeStatic(Type.getType(org.evosuite.runtime.System.class),
                    Method.getMethod("int identityHashCode(Object)"));
            mg.returnValue();
            mg.endMethod();
        }

    }

    /*
     * If the class is serializable, then doing any change (adding hashCode, static reset, etc)
     * will change the serialVersionUID if it is not defined in the class.
     * Hence, if it is not defined, we have to define it to
     * avoid problems in serialising the class, as reading Master will not do instrumentation.
     * The serialVersionUID HAS to be the same as the un-instrumented class
     */
    if (!definesUid && !isInterface && RuntimeSettings.applyUIDTransformation) {
        ClassLoader threadCL = Thread.currentThread().getContextClassLoader();
        try {
            ClassLoader evoCL = MethodCallReplacementClassAdapter.class.getClassLoader();
            Thread.currentThread().setContextClassLoader(evoCL);

            Class<?> clazz = Class.forName(className.replace('/', '.'), false, evoCL);

            if (Serializable.class.isAssignableFrom(clazz)) {
                ObjectStreamClass c = ObjectStreamClass.lookup(clazz);
                long serialID = c.getSerialVersionUID();
                logger.info("Adding serialId to class " + className);
                visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, "serialVersionUID",
                        "J", null, serialID);
            }
        } catch (ClassNotFoundException e) {
            logger.warn("Failed to add serialId to class " + className + ": " + e.getMessage());
        } catch (NoClassDefFoundError e) {
            logger.warn("Failed to add serialId to class " + className + ": " + e.getMessage());

        } finally {
            Thread.currentThread().setContextClassLoader(threadCL);
        }
    }

    super.visitEnd();
}