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:de.enough.polish.postcompile.java5.Java5ClassVisitor.java

License:Open Source License

public void visitEnd() {
    if (this.isEnumClass) {
        if (this.name_values == null) {
            throw new BuildException("This is not an enum class: " + this.classDesc);
        }//w w  w.  ja  v a 2 s.  c  o m

        // Generate new <clinit> method.
        int numValues = EnumManager.getInstance().getNumEnumValues(this.classDesc);
        Method m = Method.getMethod("void <clinit> ()");
        MethodVisitor mv = super.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
        GeneratorAdapter mg = new GeneratorAdapter(ACC_STATIC, m, mv);
        mg.push(numValues);
        mg.newArray(Type.INT_TYPE);

        if (numValues <= 3) {
            for (int i = 1; i < numValues; i++) {
                mg.dup();
                mg.push(i);
                mg.push(i);
                mg.arrayStore(Type.INT_TYPE);
            }
        } else {
            Label labelInitializeField = new Label();
            Label labelCheck = new Label();
            Label labelDone = new Label();

            mg.push(1);
            mg.storeLocal(0, Type.INT_TYPE);
            mg.goTo(labelCheck);

            mg.mark(labelInitializeField);
            mg.dup();
            mg.loadLocal(0, Type.INT_TYPE);
            mg.dup();
            mg.arrayStore(Type.INT_TYPE);
            mg.iinc(0, 1);

            mg.mark(labelCheck);
            mg.loadLocal(0, Type.INT_TYPE);
            mg.push(numValues);
            mg.ifICmp(GeneratorAdapter.LT, labelInitializeField);

            mg.mark(labelDone);
        }

        mg.putStatic(Type.getType(this.classDesc), this.name_values, Type.getType(int[].class));
        mg.returnValue();
        mg.endMethod();
    }

    // Called super implementation of this method to really close this class.
    super.visitEnd();
}

From source file:dodola.anole.lib.Redirection.java

License:Apache License

/**
 * Adds the instructions to do a generic redirection.
 * <p/>/*from w w w . j ava  2  s  .c o  m*/
 * Note that the generated bytecode does not have a direct translation to code, but as an
 * example, the following code block gets inserted.
 * <code>
 * if ($change != null) {
 * $change.access$dispatch($name, new object[] { arg0, ... argsN })
 * $anyCodeInsertedbyRestore
 * }
 * $originalMethodBody
 * </code>
 *
 * @param mv     the method visitor to add the instructions to.
 * @param change the local variable containing the alternate implementation.
 * @param args   the type of the local variable that need to be forwarded.
 */
void redirect(GeneratorAdapter mv, int change, List<Type> args) {
    // code to check if a new implementation of the current class is available.
    Label l0 = new Label();
    mv.loadLocal(change);
    mv.visitJumpInsn(Opcodes.IFNULL, l0);
    mv.loadLocal(change);
    mv.push(name);

    // create an array of objects capable of containing all the parameters and optionally the "this"
    createLocals(mv, args);

    // we need to maintain the stack index when loading parameters from, as for long and double
    // values, it uses 2 stack elements, all others use only 1 stack element.
    int stackIndex = 0;
    for (int arrayIndex = 0; arrayIndex < args.size(); arrayIndex++) {
        Type arg = args.get(arrayIndex);
        // duplicate the array of objects reference, it will be used to store the value in.
        mv.dup();
        // index in the array of objects to store the boxed parameter.
        mv.push(arrayIndex);
        // Pushes the appropriate local variable on the stack
        redirectLocal(mv, stackIndex, arg);
        // potentially box up intrinsic types.
        mv.box(arg);
        mv.arrayStore(Type.getType(Object.class));
        // stack index must progress according to the parameter type we just processed.
        stackIndex += arg.getSize();
    }

    // now invoke the generic dispatch method.
    mv.invokeInterface(IncrementalVisitor.CHANGE_TYPE,
            Method.getMethod("Object access$dispatch(String, Object[])"));

    // Restore the state after the redirection
    restore(mv, args);
    // jump label for classes without any new implementation, just invoke the original
    // method implementation.
    mv.visitLabel(l0);
}

From source file:dodola.anole.lib.StringSwitch.java

License:Apache License

/**
 * Emit code for a string if-else block.
 *
 *     if (s.equals("collided_method1")) {
 *         visit(s);/*ww  w . ja  va  2s. com*/
 *     } else if (s.equals("collided_method2")) {
 *         visit(s);
 *     }
 *
 * In the most common case of just one string, this degenerates to:
 *
 *      visit(s)
 *
 */
private void visitx(GeneratorAdapter mv, List<String> strings) {
    if (strings.size() == 1) {
        visitCase(strings.get(0));
        return;
    }
    for (int i = 0; i < strings.size(); ++i) {
        String string = strings.get(i);
        Label label = new Label();
        visitString();
        mv.visitLdcInsn(string);
        mv.invokeVirtual(STRING_TYPE, Method.getMethod("boolean equals(Object)"));
        mv.visitJumpInsn(Opcodes.IFEQ, label);
        visitCase(string);
        mv.visitLabel(label);
    }

    visitDefault();
}

From source file:io.datakernel.codegen.AsmBuilder.java

License:Apache License

/**
 * Creates a new method for a dynamic class. The method must be part of the provided interfaces or abstract class.
 *
 * @param methodName name of method// w  w w. j a  v a  2 s . c om
 * @param expression function which will be processed
 * @return changed AsmFunctionFactory
 */
public AsmBuilder<T> method(String methodName, Expression expression) {
    if (methodName.contains("(")) {
        Method method = Method.getMethod(methodName);
        return method(method, expression);
    }

    Method foundMethod = null;
    List<List<java.lang.reflect.Method>> listOfMethods = new ArrayList<>();
    listOfMethods.add(asList(Object.class.getMethods()));
    for (Class<?> type : scope.getParentClasses()) {
        listOfMethods.add(asList(type.getMethods()));
        listOfMethods.add(asList(type.getDeclaredMethods()));
    }
    for (List<java.lang.reflect.Method> list : listOfMethods) {
        for (java.lang.reflect.Method m : list) {
            if (m.getName().equals(methodName)) {
                Method method = getMethod(m);
                if (foundMethod != null && !method.equals(foundMethod))
                    throw new IllegalArgumentException("Method " + method + " collides with " + foundMethod);
                foundMethod = method;
            }
        }
    }
    Preconditions.check(foundMethod != null, "Could not find method '" + methodName + "'");
    return method(foundMethod, expression);
}

From source file:io.datakernel.codegen.ClassScope.java

License:Apache License

private void addNonPrivateMethod(java.lang.reflect.Method[] arr) {
    for (java.lang.reflect.Method e : arr) {
        if (Modifier.isPrivate(e.getModifiers()))
            continue;

        if (Modifier.isStatic(e.getModifiers()))
            staticMethods.add(Method.getMethod(e));
        else/*from   w w w  .  j a  v a 2  s .  c  o  m*/
            methods.add(Method.getMethod(e));
    }
}

From source file:io.datakernel.codegen.ClassScope.java

License:Apache License

private void collectMembers(Class<?> type) {
    parentClasses.add(type);//from   ww  w . ja  va  2 s.c om
    if (type.isInterface()) {
        recursiveAddInterfaceMethodsToList(type);
        return;
    }
    boolean search = true;
    for (Constructor<?> constructor : type.getDeclaredConstructors()) {
        if (Modifier.isPrivate(constructor.getModifiers()))
            continue;
        int length = constructor.getParameterTypes().length;
        if (search) {
            switch (length) {
            case 0:
                constructors.add(0, Method.getMethod(constructor));
                search = false;
                break;
            case 1:
                constructors.add(0, Method.getMethod(constructor));
                break;
            default:
                constructors.add(Method.getMethod(constructor));
                break;
            }
        }
    }
    Class<?> nextClass = type;
    while (nextClass != Object.class) {
        addNonPrivateField(nextClass.getDeclaredFields());
        addNonPrivateMethod(nextClass.getDeclaredMethods());
        for (Class<?> nextInterface : nextClass.getInterfaces())
            recursiveAddInterfaceMethodsToList(nextInterface);
        nextClass = nextClass.getSuperclass();
    }
}

From source file:net.wpm.codegen.ClassBuilder.java

License:Apache License

/**
 * Creates a new method for a dynamic class. The method must be part of the provided interfaces or abstract class.
 *
 * @param methodName name of method//from ww w . ja  va  2s.  com
 * @param expression function which will be processed
 * @return changed AsmFunctionFactory
 */
public ClassBuilder<T> method(String methodName, Expression expression) {
    if (methodName.contains("(")) {
        Method method = Method.getMethod(methodName);
        return method(method, expression);
    }

    Method foundMethod = null;
    List<List<java.lang.reflect.Method>> listOfMethods = new ArrayList<List<java.lang.reflect.Method>>();
    listOfMethods.add(asList(Object.class.getMethods()));
    for (Class<?> type : scope.getParentClasses()) {
        listOfMethods.add(asList(type.getMethods()));
        listOfMethods.add(asList(type.getDeclaredMethods()));
    }
    for (List<java.lang.reflect.Method> list : listOfMethods) {
        for (java.lang.reflect.Method m : list) {
            if (m.getName().equals(methodName)) {
                Method method = getMethod(m);
                if (foundMethod != null && !method.equals(foundMethod))
                    throw new IllegalArgumentException("Method " + method + " collides with " + foundMethod);
                foundMethod = method;
            }
        }
    }
    Preconditions.check(foundMethod != null, "Could not find method '" + methodName + "'");
    return method(foundMethod, expression);
}

From source file:org.apache.aries.proxy.impl.gen.ProxySubclassAdapter.java

License:Apache License

public void visit(int version, int access, String name, String signature, String superName,
        String[] interfaces) {/*w w  w. j av  a  2  s.  c o m*/
    LOGGER.debug(Constants.LOG_ENTRY, "visit",
            new Object[] { version, access, name, signature, superName, interfaces });

    // store the superclass binary name
    this.superclassBinaryName = name.replaceAll("/", "\\.");

    try {
        this.superclassClass = Class.forName(superclassBinaryName, false, loader);
    } catch (ClassNotFoundException cnfe) {
        throw new TypeNotPresentException(superclassBinaryName, cnfe);
    }

    // keep the same access and signature as the superclass (unless it's abstract)
    // remove all the superclass interfaces because they will be inherited
    // from the superclass anyway
    if ((access & ACC_ABSTRACT) != 0) {
        //If the super was abstract the subclass should not be!
        access &= ~ACC_ABSTRACT;
    }
    cv.visit(ProxyUtils.getWeavingJavaVersion(), access, newClassName, signature, name, null);

    // add a private field for the invocation handler
    // this isn't static in case we have multiple instances of the same
    // proxy
    cv.visitField(ACC_PRIVATE, IH_FIELD, Type.getDescriptor(InvocationHandler.class), null, null);

    // create a static adapter for generating a static initialiser method in
    // the generated subclass
    staticAdapter = new GeneratorAdapter(ACC_STATIC, new Method("<clinit>", Type.VOID_TYPE, NO_ARGS), null,
            null, cv);

    // add a zero args constructor method
    Method m = new Method("<init>", Type.VOID_TYPE, NO_ARGS);
    GeneratorAdapter methodAdapter = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cv);
    // loadthis
    methodAdapter.loadThis();
    // List the constructors in the superclass.
    Constructor<?>[] constructors = superclassClass.getDeclaredConstructors();
    // Check that we've got at least one constructor, and get the 1st one in the list.
    if (constructors.length > 0) {
        // We now need to construct the proxy class as though it is going to invoke the superclasses constructor.
        // We do this because we can no longer call the java.lang.Object() zero arg constructor as the JVM now throws a VerifyError.
        // So what we do is build up the calling of the superclasses constructor using nulls and default values. This means that the 
        // class bytes can be verified by the JVM, and then in the ProxySubclassGenerator, we load the class without invoking the 
        // constructor. 
        Method constructor = Method.getMethod(constructors[0]);
        Type[] argTypes = constructor.getArgumentTypes();
        if (argTypes.length == 0) {
            methodAdapter.invokeConstructor(Type.getType(superclassClass),
                    new Method("<init>", Type.VOID_TYPE, NO_ARGS));
        } else {
            for (Type type : argTypes) {
                switch (type.getSort()) {
                case Type.ARRAY:
                    // We need to process any array or multidimentional arrays.
                    String elementDesc = type.getElementType().getDescriptor();
                    String typeDesc = type.getDescriptor();

                    // Iterate over the number of arrays and load 0 for each one. Keep a count of the number of 
                    // arrays as we will need to run different code fo multi dimentional arrays.
                    int index = 0;
                    while (!elementDesc.equals(typeDesc)) {
                        typeDesc = typeDesc.substring(1);
                        methodAdapter.visitInsn(Opcodes.ICONST_0);
                        index++;
                    }
                    // If we're just a single array, then call the newArray method, otherwise use the MultiANewArray instruction.
                    if (index == 1) {
                        methodAdapter.newArray(type.getElementType());
                    } else {
                        methodAdapter.visitMultiANewArrayInsn(type.getDescriptor(), index);
                    }
                    break;
                case Type.BOOLEAN:
                    methodAdapter.push(true);
                    break;
                case Type.BYTE:
                    methodAdapter.push(Type.VOID_TYPE);
                    break;
                case Type.CHAR:
                    methodAdapter.push(Type.VOID_TYPE);
                    break;
                case Type.DOUBLE:
                    methodAdapter.push(0.0);
                    break;
                case Type.FLOAT:
                    methodAdapter.push(0.0f);
                    break;
                case Type.INT:
                    methodAdapter.push(0);
                    break;
                case Type.LONG:
                    methodAdapter.push(0l);
                    break;
                case Type.SHORT:
                    methodAdapter.push(0);
                    break;
                default:
                case Type.OBJECT:
                    methodAdapter.visitInsn(Opcodes.ACONST_NULL);
                    break;
                }
            }

            methodAdapter.invokeConstructor(Type.getType(superclassClass),
                    new Method("<init>", Type.VOID_TYPE, argTypes));
        }
    }
    methodAdapter.returnValue();
    methodAdapter.endMethod();

    // add a method for getting the invocation handler
    Method setter = new Method("setInvocationHandler", Type.VOID_TYPE, new Type[] { IH_TYPE });
    m = new Method("getInvocationHandler", IH_TYPE, NO_ARGS);
    methodAdapter = new GeneratorAdapter(ACC_PUBLIC | ACC_FINAL, m, null, null, cv);
    // load this to get the field
    methodAdapter.loadThis();
    // get the ih field and return
    methodAdapter.getField(newClassType, IH_FIELD, IH_TYPE);
    methodAdapter.returnValue();
    methodAdapter.endMethod();

    // add a method for setting the invocation handler
    methodAdapter = new GeneratorAdapter(ACC_PUBLIC | ACC_FINAL, setter, null, null, cv);
    // load this to put the field
    methodAdapter.loadThis();
    // load the method arguments (i.e. the invocation handler) to the stack
    methodAdapter.loadArgs();
    // set the ih field using the method argument
    methodAdapter.putField(newClassType, IH_FIELD, IH_TYPE);
    methodAdapter.returnValue();
    methodAdapter.endMethod();

    // loop through the class hierarchy to get any needed methods off the
    // supertypes
    // start by finding the methods declared on the class of interest (the
    // superclass of our dynamic subclass)
    java.lang.reflect.Method[] observedMethods = superclassClass.getDeclaredMethods();
    // add the methods to a set of observedMethods
    ProxySubclassMethodHashSet<String> setOfObservedMethods = new ProxySubclassMethodHashSet<String>(
            observedMethods.length);
    setOfObservedMethods.addMethodArray(observedMethods);
    // get the next superclass in the hierarchy
    Class<?> nextSuperClass = superclassClass.getSuperclass();
    while (nextSuperClass != null) {
        // set the fields for the current class
        setCurrentAnalysisClassFields(nextSuperClass);

        // add a static field and static initializer code to the generated
        // subclass
        // for each of the superclasses in the hierarchy
        addClassStaticField(currentlyAnalysedClassName);

        LOGGER.debug("Class currently being analysed: {} {}", currentlyAnalysedClassName,
                currentlyAnalysedClass);

        // now find the methods declared on the current class and add them
        // to a set of foundMethods
        java.lang.reflect.Method[] foundMethods = currentlyAnalysedClass.getDeclaredMethods();
        ProxySubclassMethodHashSet<String> setOfFoundMethods = new ProxySubclassMethodHashSet<String>(
                foundMethods.length);
        setOfFoundMethods.addMethodArray(foundMethods);
        // remove from the set of foundMethods any methods we saw on a
        // subclass
        // because we want to use the lowest level declaration of a method
        setOfFoundMethods.removeAll(setOfObservedMethods);
        try {
            // read the current class and use a
            // ProxySubclassHierarchyAdapter
            // to process only methods on that class that are in the list
            ClassLoader loader = currentlyAnalysedClass.getClassLoader();
            if (loader == null) {
                loader = this.loader;
            }
            ClassReader cr = new ClassReader(loader
                    .getResourceAsStream(currentlyAnalysedClass.getName().replaceAll("\\.", "/") + ".class"));
            ClassVisitor hierarchyAdapter = new ProxySubclassHierarchyAdapter(this, setOfFoundMethods);
            cr.accept(hierarchyAdapter, ClassReader.SKIP_DEBUG);
        } catch (IOException e) {
            throw new TypeNotPresentException(currentlyAnalysedClassName, e);
        }
        // now add the foundMethods to the overall list of observed methods
        setOfObservedMethods.addAll(setOfFoundMethods);
        // get the next class up in the hierarchy and go again
        nextSuperClass = currentlyAnalysedClass.getSuperclass();
    }

    // we've finished looking at the superclass hierarchy
    // set the fields for the immediate superclass of our dynamic subclass
    setCurrentAnalysisClassFields(superclassClass);

    // add the class static field
    addClassStaticField(currentlyAnalysedClassName);
    // we do the lowest class last because we are already visiting the class
    // when in this adapter code
    // now we are ready to visit all the methods on the lowest class
    // which will happen by the ASM ClassVisitor implemented in this adapter

    LOGGER.debug(Constants.LOG_EXIT, "visit");
}

From source file:org.apache.aries.proxy.impl.interfaces.InterfaceCombiningClassAdapter.java

License:Apache License

private void visitAbstractMethods(Class<?> clazz) {
    for (java.lang.reflect.Method m : clazz.getDeclaredMethods()) {
        int modifiers = m.getModifiers();
        if ((modifiers & Modifier.ABSTRACT) != 0) {
            List<String> exceptions = new ArrayList<String>();
            for (Class<?> c : m.getExceptionTypes()) {
                exceptions.add(Type.getInternalName(c));
            }// ww  w.ja v  a  2 s.  c  o  m
            MethodVisitor visitor = visitMethod(modifiers, m.getName(), Method.getMethod(m).getDescriptor(),
                    null, exceptions.toArray(new String[exceptions.size()]));
            if (visitor != null)
                visitor.visitEnd();
        }
    }
}

From source file:org.apache.commons.weaver.privilizer.ActionGenerator.java

License:Apache License

/**
 * Add fields and generate constructor./*  w w w . jav  a 2  s  . c  om*/
 */
private void init() {
    for (final Field field : fields) {
        visitField(field.access, field.name, field.type.getDescriptor(), null, null).visitEnd();
    }
    final Method init = new Method("<init>", Type.VOID_TYPE, helper.getArgumentTypes());

    final GeneratorAdapter mgen = new GeneratorAdapter(0, init, null, Privilizer.EMPTY_TYPE_ARRAY, this);

    mgen.visitCode();
    final Label begin = mgen.mark();

    // invoke super constructor
    mgen.loadThis();
    mgen.invokeConstructor(Type.getType(Object.class), Method.getMethod("void <init> ()"));
    // assign remaining fields

    int arg = 0;
    for (final Field field : fields) {
        mgen.loadThis();
        mgen.loadArg(arg++);
        mgen.putField(action, field.name, field.type);
    }
    mgen.returnValue();
    final Label end = mgen.mark();

    // declare local vars
    mgen.visitLocalVariable("this", action.getDescriptor(), null, begin, end, 0);
    arg = 1;
    for (final Field field : fields) {
        mgen.visitLocalVariable("arg" + arg, field.type.getDescriptor(), null, begin, end, arg++);
    }
    mgen.endMethod();
}