Example usage for org.objectweb.asm.tree MethodNode MethodNode

List of usage examples for org.objectweb.asm.tree MethodNode MethodNode

Introduction

In this page you can find the example usage for org.objectweb.asm.tree MethodNode MethodNode.

Prototype

public MethodNode(final int access, final String name, final String descriptor, final String signature,
        final String[] exceptions) 

Source Link

Document

Constructs a new MethodNode .

Usage

From source file:com.liferay.portal.nio.intraband.proxy.IntrabandProxyUtilTest.java

License:Open Source License

@Test
public void testSerializerWrite() {
    MethodNode methodNode = new MethodNode(Opcodes.ACC_PUBLIC, "name", "()V", null, null);

    MethodNodeGenerator methodNodeGenerator = new MethodNodeGenerator(methodNode);

    InsnList insnList = methodNode.instructions;

    for (Type type : _types) {
        IntrabandProxyUtil.serializerWrite(methodNodeGenerator, type);

        AbstractInsnNode abstractInsnNode = insnList.getLast();

        Assert.assertTrue(abstractInsnNode instanceof MethodInsnNode);

        MethodInsnNode methodInsnNode = (MethodInsnNode) abstractInsnNode;

        Assert.assertEquals(Opcodes.INVOKEVIRTUAL, abstractInsnNode.getOpcode());
        Assert.assertEquals(Type.getInternalName(Serializer.class), methodInsnNode.owner);

        if (type.getSort() <= Type.DOUBLE) {
            String name = TextFormatter.format(type.getClassName(), TextFormatter.G);

            Assert.assertEquals("write".concat(name), methodInsnNode.name);
            Assert.assertEquals(Type.getMethodDescriptor(Type.VOID_TYPE, type), methodInsnNode.desc);
        } else if (type.equals(Type.getType(String.class))) {
            Assert.assertEquals("writeString", methodInsnNode.name);
            Assert.assertEquals(Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)),
                    methodInsnNode.desc);
        } else {// w w w  .  j  a va  2s  .co m
            Assert.assertEquals("writeObject", methodInsnNode.name);
            Assert.assertEquals(Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Serializable.class)),
                    methodInsnNode.desc);
        }
    }
}

From source file:com.liferay.portal.nio.intraband.proxy.IntrabandProxyUtilTest.java

License:Open Source License

private void _doTestToClass(boolean proxyClassesDumpEnabled, boolean logEnabled) throws FileNotFoundException {

    class TestClass {
    }//from  w  ww.  j  a  v  a 2  s.  c o  m

    ClassNode classNode = _loadClass(TestClass.class);

    MethodNode methodNode = new MethodNode(Opcodes.ACC_PUBLIC, "<clinit>", "()V", null, null);

    methodNode.visitCode();
    methodNode.visitInsn(Opcodes.RETURN);
    methodNode.visitEnd();

    List<MethodNode> methodNodes = classNode.methods;

    methodNodes.add(methodNode);

    ClassLoader classLoader = new URLClassLoader(new URL[0], null);

    Level level = Level.WARNING;

    if (logEnabled) {
        level = Level.INFO;
    }

    try (CaptureHandler captureHandler = JDKLoggerTestUtil
            .configureJDKLogger(IntrabandProxyUtil.class.getName(), level)) {

        List<LogRecord> logRecords = captureHandler.getLogRecords();

        IntrabandProxyUtil.toClass(classNode, classLoader);

        if (proxyClassesDumpEnabled) {
            StringBundler sb = new StringBundler(6);

            sb.append(SystemProperties.get(SystemProperties.TMP_DIR));
            sb.append(StringPool.SLASH);
            sb.append(PropsValues.INTRABAND_PROXY_DUMP_CLASSES_DIR);
            sb.append(StringPool.SLASH);
            sb.append(classNode.name);
            sb.append(".class");

            String filePath = sb.toString();

            File classFile = new File(filePath);

            Assert.assertTrue(classFile.exists());

            ClassNode reloadedClassNode = _loadClass(new FileInputStream(classFile));

            MethodNode clinitMethodNode = ASMUtil.findMethodNode(reloadedClassNode.methods, "<clinit>",
                    Type.VOID_TYPE);

            InsnList insnList = clinitMethodNode.instructions;

            Assert.assertEquals(1, insnList.size());

            _assertInsnNode(insnList.getFirst(), Opcodes.RETURN);

            if (logEnabled) {
                Assert.assertEquals(1, logRecords.size());

                LogRecord logRecord = logRecords.get(0);

                Assert.assertEquals(logRecord.getMessage(), "Dumpped class ".concat(filePath));
            }
        }

        if (!proxyClassesDumpEnabled || !logEnabled) {
            Assert.assertTrue(logRecords.isEmpty());
        }
    }

    try {
        IntrabandProxyUtil.toClass(classNode, classLoader);

        Assert.fail();
    } catch (RuntimeException re) {
        Throwable throwable = re.getCause();

        Assert.assertSame(InvocationTargetException.class, throwable.getClass());

        throwable = throwable.getCause();

        Assert.assertSame(LinkageError.class, throwable.getClass());

        String message = throwable.getMessage();

        Assert.assertTrue(message.contains(
                "duplicate class definition for name: \"" + Type.getInternalName(TestClass.class) + "\""));
    }
}

From source file:com.lodgon.parboiled.transform.ClassNodeInitializer.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    if ("<init>".equals(name)) {
        // do not add constructors from super classes or private constructors
        if (ownerClass != classNode.getParentClass() || (access & ACC_PRIVATE) > 0) {
            return null;
        }//from   www  .j  a va  2 s .  c  om
        MethodNode constructor = new MethodNode(access, name, desc, signature, exceptions);
        classNode.getConstructors().add(constructor);
        return constructor; // return the newly created method in order to have it "filled" with the method code
    }

    // only add non-native, non-abstract methods returning Rules
    if (!Type.getReturnType(desc).equals(Types.RULE) || (access & (ACC_NATIVE | ACC_ABSTRACT)) > 0) {
        return null;
    }

    Checks.ensure((access & ACC_PRIVATE) == 0,
            "Rule method '%s'must not be private.\n"
                    + "Mark the method protected or package-private if you want to prevent public access!",
            name);
    Checks.ensure((access & ACC_FINAL) == 0, "Rule method '%s' must not be final.", name);

    // check, whether we do not already have a method with that name and descriptor
    // if we do we add the method with a "$" prefix in order to have it processed and be able to reference it
    // later if we have to
    String methodKey = name.concat(desc);
    while (classNode.getRuleMethods().containsKey(methodKey)) {
        name = '$' + name;
        methodKey = name.concat(desc);
    }

    RuleMethod method = new RuleMethod(ownerClass, access, name, desc, signature, exceptions,
            hasExplicitActionOnlyAnnotation, hasDontLabelAnnotation, hasSkipActionsInPredicates);
    classNode.getRuleMethods().put(methodKey, method);
    return method; // return the newly created method in order to have it "filled" with the actual method code
}

From source file:com.lodgon.parboiled.transform.ConstructorGenerator.java

License:Apache License

@SuppressWarnings({ "unchecked" })
private void createConstuctor(ParserClassNode classNode, MethodNode constructor) {
    MethodNode newConstructor = new MethodNode(ACC_PUBLIC, constructor.name, constructor.desc,
            constructor.signature,//from ww w . j a v  a 2  s . c om
            (String[]) constructor.exceptions.toArray(new String[constructor.exceptions.size()]));

    InsnList instructions = newConstructor.instructions;
    instructions.add(new VarInsnNode(ALOAD, 0));
    instructions.add(createArgumentLoaders(constructor.desc));
    instructions.add(new MethodInsnNode(INVOKESPECIAL, classNode.getParentType().getInternalName(), "<init>",
            constructor.desc));
    instructions.add(new InsnNode(RETURN));

    classNode.methods.add(newConstructor);
}

From source file:com.lodgon.parboiled.transform.ConstructorGenerator.java

License:Apache License

@SuppressWarnings({ "unchecked" })
private void createNewInstanceMethod(ParserClassNode classNode) {
    MethodNode method = new MethodNode(ACC_PUBLIC, "newInstance",
            "()L" + Types.BASE_PARSER.getInternalName() + ';', null, null);
    InsnList instructions = method.instructions;
    instructions.add(new TypeInsnNode(NEW, classNode.name));
    instructions.add(new InsnNode(DUP));
    instructions.add(new MethodInsnNode(INVOKESPECIAL, classNode.name, "<init>", "()V"));
    instructions.add(new InsnNode(ARETURN));

    classNode.methods.add(method);//from   w  w  w . j av a  2  s.  c  o  m
}

From source file:com.navercorp.pinpoint.profiler.instrument.ASMClassNodeAdapter.java

License:Apache License

public ASMMethodNodeAdapter addDelegatorMethod(final ASMMethodNodeAdapter superMethodNode) {
    if (superMethodNode == null) {
        throw new IllegalArgumentException("super method annotation must not be null.");
    }//from w  w w . j av a 2  s  .  c o  m

    String[] exceptions = null;
    if (superMethodNode.getExceptions() != null) {
        exceptions = superMethodNode.getExceptions()
                .toArray(new String[superMethodNode.getExceptions().size()]);
    }

    final ASMMethodNodeAdapter methodNode = new ASMMethodNodeAdapter(getInternalName(),
            new MethodNode(superMethodNode.getAccess(), superMethodNode.getName(), superMethodNode.getDesc(),
                    superMethodNode.getSignature(), exceptions));
    methodNode.addDelegator(superMethodNode.getDeclaringClassInternalName());
    if (this.classNode.methods == null) {
        this.classNode.methods = new ArrayList<MethodNode>();
    }
    this.classNode.methods.add(methodNode.getMethodNode());

    return methodNode;
}

From source file:com.navercorp.pinpoint.profiler.instrument.ASMClassNodeAdapter.java

License:Apache License

public void addGetterMethod(final String methodName, final ASMFieldNodeAdapter fieldNode) {
    if (methodName == null || fieldNode == null) {
        throw new IllegalArgumentException("method name or fieldNode annotation must not be null.");
    }/*  w  ww. j ava 2  s. c o m*/

    // no argument is ().
    final String desc = "()" + fieldNode.getDesc();
    final MethodNode methodNode = new MethodNode(Opcodes.ACC_PUBLIC, methodName, desc, null, null);
    if (methodNode.instructions == null) {
        methodNode.instructions = new InsnList();
    }
    final InsnList instructions = methodNode.instructions;
    // load this.
    instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
    // get fieldNode.
    instructions
            .add(new FieldInsnNode(Opcodes.GETFIELD, classNode.name, fieldNode.getName(), fieldNode.getDesc()));
    // return of type.
    final Type type = Type.getType(fieldNode.getDesc());
    instructions.add(new InsnNode(type.getOpcode(Opcodes.IRETURN)));

    if (this.classNode.methods == null) {
        this.classNode.methods = new ArrayList<MethodNode>();
    }
    this.classNode.methods.add(methodNode);
}

From source file:com.navercorp.pinpoint.profiler.instrument.ASMClassNodeAdapter.java

License:Apache License

public void addSetterMethod(final String methodName, final ASMFieldNodeAdapter fieldNode) {
    if (methodName == null || fieldNode == null) {
        throw new IllegalArgumentException("method name or fieldNode annotation must not be null.");
    }//from w w w.  jav a2 s. c  o  m

    // void is V.
    final String desc = "(" + fieldNode.getDesc() + ")V";
    final MethodNode methodNode = new MethodNode(Opcodes.ACC_PUBLIC, methodName, desc, null, null);
    if (methodNode.instructions == null) {
        methodNode.instructions = new InsnList();
    }
    final InsnList instructions = methodNode.instructions;
    // load this.
    instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
    final Type type = Type.getType(fieldNode.getDesc());
    // put field.
    instructions.add(new VarInsnNode(type.getOpcode(Opcodes.ILOAD), 1));
    instructions
            .add(new FieldInsnNode(Opcodes.PUTFIELD, classNode.name, fieldNode.getName(), fieldNode.getDesc()));
    // return.
    instructions.add(new InsnNode(Opcodes.RETURN));

    if (this.classNode.methods == null) {
        this.classNode.methods = new ArrayList<MethodNode>();
    }
    this.classNode.methods.add(methodNode);
}

From source file:com.navercorp.pinpoint.profiler.instrument.ASMMethodNodeAdapterAddDelegatorTest.java

License:Apache License

private Class<?> addDelegatorMethod(final String targetClassName, final String superClassName,
        final String methodName) throws Exception {
    final ClassNode superClassNode = ASMClassNodeLoader.get(superClassName);
    List<MethodNode> methodNodes = superClassNode.methods;
    final MethodNode methodNode = findMethodNode(methodName, methodNodes);

    classLoader.setTargetClassName(targetClassName);
    classLoader.setCallbackHandler(new ASMClassNodeLoader.CallbackHandler() {
        @Override/* ww  w. ja  va 2 s .  c o m*/
        public void handle(final ClassNode classNode) {
            String[] exceptions = null;
            if (methodNode.exceptions != null) {
                exceptions = methodNode.exceptions.toArray(new String[methodNode.exceptions.size()]);
            }

            final MethodNode newMethodNode = new MethodNode(methodNode.access, methodNode.name, methodNode.desc,
                    methodNode.signature, exceptions);
            final ASMMethodNodeAdapter methodNodeAdapter = new ASMMethodNodeAdapter(targetClassName,
                    newMethodNode);
            methodNodeAdapter.addDelegator(superClassName.replace('.', '/'));
            classNode.methods.add(newMethodNode);
        }
    });
    return classLoader.loadClass(targetClassName);
}

From source file:com.seovic.pof.PortableTypeGenerator.java

License:Apache License

private void implementDefaultConstructor() {
    MethodNode ctor = findMethod("<init>", "()V");
    if (ctor == null) {
        ctor = new MethodNode(ACC_PUBLIC, "<init>", "()V", null, null);

        ctor.visitCode();//from   w w w  .  j a  va  2s  .c om
        ctor.visitVarInsn(ALOAD, 0);
        ctor.visitMethodInsn(INVOKESPECIAL, cn.superName, "<init>", "()V");
        ctor.visitInsn(RETURN);
        ctor.visitMaxs(1, 1);
        ctor.visitEnd();

        cn.methods.add(ctor);
    } else if ((ctor.access & ACC_PUBLIC) == 0) {
        LOG.info("Class " + cn.name + " has a non-public default constructor. Making it public.");
        ctor.access = ACC_PUBLIC;
    }
}