Example usage for org.objectweb.asm Opcodes ACC_SYNTHETIC

List of usage examples for org.objectweb.asm Opcodes ACC_SYNTHETIC

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes ACC_SYNTHETIC.

Prototype

int ACC_SYNTHETIC

To view the source code for org.objectweb.asm Opcodes ACC_SYNTHETIC.

Click Source Link

Usage

From source file:gnu.classpath.tools.rmic.ClassRmicCompiler.java

License:Open Source License

private static void generateClassForNamer(ClassVisitor cls) {
    MethodVisitor cv = cls.visitMethod(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_SYNTHETIC,
            forName,//  w  ww  .  j  av a2  s . co m
            Type.getMethodDescriptor(Type.getType(Class.class), new Type[] { Type.getType(String.class) }),
            null, null);

    Label start = new Label();
    cv.visitLabel(start);
    cv.visitVarInsn(Opcodes.ALOAD, 0);
    cv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Class.class), "forName",
            Type.getMethodDescriptor(Type.getType(Class.class), new Type[] { Type.getType(String.class) }));
    cv.visitInsn(Opcodes.ARETURN);

    Label handler = new Label();
    cv.visitLabel(handler);
    cv.visitVarInsn(Opcodes.ASTORE, 1);
    cv.visitTypeInsn(Opcodes.NEW, typeArg(NoClassDefFoundError.class));
    cv.visitInsn(Opcodes.DUP);
    cv.visitVarInsn(Opcodes.ALOAD, 1);
    cv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(ClassNotFoundException.class), "getMessage",
            Type.getMethodDescriptor(Type.getType(String.class), new Type[] {}));
    cv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(NoClassDefFoundError.class), "<init>",
            Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(String.class) }));
    cv.visitInsn(Opcodes.ATHROW);
    cv.visitTryCatchBlock(start, handler, handler, Type.getInternalName(ClassNotFoundException.class));
    cv.visitMaxs(-1, -1);
}

From source file:graph.Modifier.java

License:Apache License

/**
 * Returns an integer bit field for the EnumSet, where the bit values are
 * defined as in the class file format.//from w  w w . j  ava2  s.c om
 *
 * @param  set   Set of modifiers to convert to a bit field.
 * @return       Integer bit field.
 */
public static int getBitField(EnumSet<Modifier> set) {
    int access = 0;

    if (set.contains(PUBLIC)) {
        access |= Opcodes.ACC_PUBLIC;
    }

    if (set.contains(PROTECTED)) {
        access |= Opcodes.ACC_PROTECTED;
    }

    if (set.contains(PRIVATE)) {
        access |= Opcodes.ACC_PRIVATE;
    }

    if (set.contains(STATIC)) {
        access |= Opcodes.ACC_STATIC;
    }

    if (set.contains(FINAL)) {
        access |= Opcodes.ACC_FINAL;
    }

    if (set.contains(SUPER)) {
        access |= Opcodes.ACC_SUPER;
    }

    if (set.contains(INTERFACE)) {
        access |= Opcodes.ACC_INTERFACE;
    }

    if (set.contains(ABSTRACT)) {
        access |= Opcodes.ACC_ABSTRACT;
    }

    if (set.contains(SYNTHETIC)) {
        access |= Opcodes.ACC_SYNTHETIC;
    }

    if (set.contains(ANNOTATION)) {
        access |= Opcodes.ACC_ANNOTATION;
    }

    if (set.contains(ENUM)) {
        access |= Opcodes.ACC_ENUM;
    }

    if (set.contains(VOLATILE)) {
        access |= Opcodes.ACC_VOLATILE;
    }

    if (set.contains(TRANSIENT)) {
        access |= Opcodes.ACC_TRANSIENT;
    }

    if (set.contains(SYNCHRONIZED)) {
        access |= Opcodes.ACC_SYNCHRONIZED;
    }

    if (set.contains(BRIDGE)) {
        access |= Opcodes.ACC_BRIDGE;
    }

    if (set.contains(VARARGS)) {
        access |= Opcodes.ACC_VARARGS;
    }

    if (set.contains(NATIVE)) {
        access |= Opcodes.ACC_NATIVE;
    }

    return access;
}

From source file:graph.Modifier.java

License:Apache License

/**
 * Returns an EnumSet of the modifiers, based on the given bit field (where
 * the bit values are defined as in the class file format).
 *
 * @param access Integer bit field giving access modifiers.
 * @return       Set of modifiers.// ww w  . j  a v a 2 s . c o  m
 */
public static EnumSet<Modifier> getSet(int access) {
    EnumSet<Modifier> modifiers = EnumSet.noneOf(Modifier.class);

    if ((access & Opcodes.ACC_PUBLIC) != 0) {
        modifiers.add(Modifier.PUBLIC);
    }

    if ((access & Opcodes.ACC_PROTECTED) != 0) {
        modifiers.add(Modifier.PROTECTED);
    }

    if ((access & Opcodes.ACC_PRIVATE) != 0) {
        modifiers.add(Modifier.PRIVATE);
    }

    if ((access & Opcodes.ACC_STATIC) != 0) {
        modifiers.add(Modifier.STATIC);
    }

    if ((access & Opcodes.ACC_FINAL) != 0) {
        modifiers.add(Modifier.FINAL);
    }

    if ((access & Opcodes.ACC_SUPER) != 0) {
        modifiers.add(Modifier.SUPER);
    }

    if ((access & Opcodes.ACC_INTERFACE) != 0) {
        modifiers.add(Modifier.INTERFACE);
    }

    if ((access & Opcodes.ACC_ABSTRACT) != 0) {
        modifiers.add(Modifier.ABSTRACT);
    }

    if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
        modifiers.add(Modifier.SYNTHETIC);
    }

    if ((access & Opcodes.ACC_ANNOTATION) != 0) {
        modifiers.add(Modifier.ANNOTATION);
    }

    if ((access & Opcodes.ACC_ENUM) != 0) {
        modifiers.add(Modifier.ENUM);
    }

    if ((access & Opcodes.ACC_VOLATILE) != 0) {
        modifiers.add(Modifier.VOLATILE);
    }

    if ((access & Opcodes.ACC_TRANSIENT) != 0) {
        modifiers.add(Modifier.TRANSIENT);
    }

    if ((access & Opcodes.ACC_SYNCHRONIZED) != 0) {
        modifiers.add(Modifier.SYNCHRONIZED);
    }

    if ((access & Opcodes.ACC_BRIDGE) != 0) {
        modifiers.add(Modifier.BRIDGE);
    }

    if ((access & Opcodes.ACC_VARARGS) != 0) {
        modifiers.add(Modifier.VARARGS);
    }

    if ((access & Opcodes.ACC_NATIVE) != 0) {
        modifiers.add(Modifier.NATIVE);
    }

    if ((access & Opcodes.ACC_STRICT) != 0) {
        modifiers.add(Modifier.STRICT);
    }

    return modifiers;
}

From source file:lombok.patcher.scripts.SetSymbolDuringMethodCallScript.java

License:Open Source License

private void makeWrapperMethod(ClassVisitor cv, WrapperMethodDescriptor wmd) {
    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC,
            wmd.getWrapperName(), wmd.getWrapperDescriptor(), null, null);

    MethodLogistics logistics = new MethodLogistics(Opcodes.ACC_STATIC, wmd.getWrapperDescriptor());

    mv.visitCode();//from w w w  .  j ava  2 s  .co  m
    Label start = new Label();
    Label end = new Label();
    Label handler = new Label();
    mv.visitTryCatchBlock(start, end, handler, null);
    mv.visitLabel(start);
    mv.visitLdcInsn(symbol);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "lombok/patcher/Symbols", "push", "(Ljava/lang/String;)V", false);
    for (int i = 0; i < logistics.getParamCount(); i++) {
        logistics.generateLoadOpcodeForParam(i, mv);
    }
    mv.visitMethodInsn(wmd.getOpcode(), wmd.getOwner(), wmd.getName(), wmd.getTargetDescriptor(), wmd.isItf());
    mv.visitLabel(end);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "lombok/patcher/Symbols", "pop", "()V", false);
    logistics.generateReturnOpcode(mv);
    mv.visitLabel(handler);
    mv.visitFrame(Opcodes.F_FULL, 0, null, 1, new Object[] { "java/lang/Throwable" });
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "lombok/patcher/Symbols", "pop", "()V", false);
    mv.visitInsn(Opcodes.ATHROW);
    mv.visitMaxs(Math.max(1, logistics.getParamCount()), logistics.getParamCount());
    mv.visitEnd();
}

From source file:net.minecraftforge.gradle.tasks.DeobfuscateJar.java

License:Open Source License

private byte[] stripSynthetics(String name, byte[] data) {
    ClassReader reader = new ClassReader(data);
    ClassNode node = new ClassNode();

    reader.accept(node, 0);// w  w  w.  j  av  a2s.  c  om

    if ((node.access & Opcodes.ACC_ENUM) == 0 && !node.superName.equals("java/lang/Enum")
            && (node.access & Opcodes.ACC_SYNTHETIC) == 0) {
        // ^^ is for ignoring enums.

        for (FieldNode f : ((List<FieldNode>) node.fields)) {
            f.access = f.access & (0xffffffff - Opcodes.ACC_SYNTHETIC);
            //getLogger().lifecycle("Stripping field: "+f.name);
        }

        for (MethodNode m : ((List<MethodNode>) node.methods)) {
            m.access = m.access & (0xffffffff - Opcodes.ACC_SYNTHETIC);
            //getLogger().lifecycle("Stripping method: "+m.name);
        }
    }

    ClassWriter writer = new ClassWriter(0);
    node.accept(writer);
    return writer.toByteArray();
}

From source file:net.sf.cglib.proxy.TestEnhancer.java

License:Apache License

public void testBridgeParameterCheckcast() throws Exception {

    // If the compiler used for Z omits the bridge method, and X is compiled with javac,
    // javac will generate an invokespecial bridge in X.

    // public interface I<A, B> {
    //   public A f(B b);
    // }/*from  w  w  w . j a v  a2s .  c  om*/
    // public abstract class Z<U extends Number> implements I<U, Long> {
    //   public U f(Long id) {
    //     return null;
    //   }
    // }
    // public class X extends Z<Integer> {}

    final Map<String, byte[]> classes = new HashMap<String, byte[]>();

    {
        ClassWriter cw = new ClassWriter(0);
        cw.visit(49, Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT | Opcodes.ACC_INTERFACE, "I",
                "<A:Ljava/lang/Object;B:Ljava/lang/Object;>Ljava/lang/Object;", "java/lang/Object", null);
        {
            MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, "f",
                    "(Ljava/lang/Object;)Ljava/lang/Object;", "(TB;)TA;", null);
            mv.visitEnd();
        }
        cw.visitEnd();
        classes.put("I.class", cw.toByteArray());
    }
    {
        ClassWriter cw = new ClassWriter(0);
        cw.visit(49, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_ABSTRACT, "Z",
                "<U:Ljava/lang/Number;>Ljava/lang/Object;LI<TU;Ljava/lang/String;>;", "java/lang/Object",
                new String[] { "I" });
        {
            MethodVisitor mv = cw.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(1, 1);
            mv.visitEnd();
        }
        {
            MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "f", "(Ljava/lang/String;)Ljava/lang/Number;",
                    "(Ljava/lang/String;)TU;", null);
            mv.visitCode();
            mv.visitInsn(Opcodes.ACONST_NULL);
            mv.visitInsn(Opcodes.ARETURN);
            mv.visitMaxs(1, 2);
            mv.visitEnd();
        }
        cw.visitEnd();
        classes.put("Z.class", cw.toByteArray());
    }
    {
        ClassWriter cw = new ClassWriter(0);
        cw.visit(49, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, "X", "LZ<Ljava/lang/Integer;>;", "Z", null);
        {
            MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
            mv.visitCode();
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "Z", "<init>", "()V", false);
            mv.visitInsn(Opcodes.RETURN);
            mv.visitMaxs(1, 1);
            mv.visitEnd();
        }
        {
            MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_BRIDGE | Opcodes.ACC_SYNTHETIC,
                    "f", "(Ljava/lang/Object;)Ljava/lang/Object;", null, null);
            mv.visitCode();
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitVarInsn(Opcodes.ALOAD, 1);
            mv.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/String");
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "Z", "f", "(Ljava/lang/String;)Ljava/lang/Number;",
                    false);
            mv.visitInsn(Opcodes.ARETURN);
            mv.visitMaxs(2, 2);
            mv.visitEnd();
        }

        cw.visitEnd();

        classes.put("X.class", cw.toByteArray());
    }

    ClassLoader classLoader = new ClassLoader(getClass().getClassLoader()) {
        @Override
        public InputStream getResourceAsStream(String name) {
            InputStream is = super.getResourceAsStream(name);
            if (is != null) {
                return is;
            }
            if (classes.containsKey(name)) {
                return new ByteArrayInputStream(classes.get(name));
            }
            return null;
        }

        public Class findClass(String name) throws ClassNotFoundException {
            byte[] ba = classes.get(name.replace('.', '/') + ".class");
            if (ba != null) {
                return defineClass(name, ba, 0, ba.length);
            }
            throw new ClassNotFoundException(name);
        }
    };

    List<Class> retTypes = new ArrayList<Class>();
    List<Class> paramTypes = new ArrayList<Class>();
    Interceptor interceptor = new Interceptor(retTypes, paramTypes);

    Enhancer e = new Enhancer();
    e.setClassLoader(classLoader);
    e.setSuperclass(classLoader.loadClass("X"));
    e.setCallback(interceptor);

    Object c = e.create();

    for (Method m : c.getClass().getDeclaredMethods()) {
        if (m.getName().equals("f") && m.getReturnType().equals(Object.class)) {
            m.invoke(c, new Object[] { null });
        }
    }

    // f(Object)Object should bridge to f(Number)String
    assertEquals(Arrays.asList(Object.class, Number.class), retTypes);
    assertEquals(Arrays.asList(Object.class, String.class), paramTypes);
}

From source file:net.sf.profiler4j.agent.BytecodeTransformer.java

License:Apache License

private static boolean canProfileMethod(Type classType, int access, String name, String desc, String signature,
        String[] exceptions, Config config, String globalName, String localName) {
    if (((access & Opcodes.ACC_ABSTRACT) | (access & Opcodes.ACC_NATIVE)
            | (access & Opcodes.ACC_SYNTHETIC)) != 0) {
        return false;
    }//  ww w .  j  av  a 2s  . com
    // if (name.equals("<init>") || name.equals("<clinit>")) {
    // return false;
    // }
    return true;
    /*List<Rule> rules = config.getRules();
    if (rules == null) {
       return false;
    }
    Rule selectedRule = null;
    for (Rule rule : rules) {
       if (rule.matches(globalName)) {
    selectedRule = rule;
    break;
       }
    }
    if (selectedRule == null) {
       return false;
    }
    if (selectedRule.getAction() == Rule.Action.ACCEPT) {
       if (selectedRule.isBooleanOptionSet(Rule.Option.BEANPROPS, config)
       && isGetterSetter(access, name, desc)) {
    return false;
       }
       boolean packageAccess = (access & 0x7) == 0;
       boolean protectedAccess = (access & Opcodes.ACC_PROTECTED) != 0;
       boolean publicAccess = (access & Opcodes.ACC_PUBLIC) != 0;
       String accessStr = selectedRule.getOption(Rule.Option.ACCESS, config);
       boolean acceptVisiblity = "private".equals(accessStr)
       || ("package".equals(accessStr) && (packageAccess || protectedAccess || publicAccess))
       || ("protected".equals(access) && (protectedAccess || publicAccess) || ("public"
       .equals(access) && publicAccess));
       return acceptVisiblity;
    }
            
    return false;   */
}

From source file:net.yrom.tools.WriteStyleablesProcessor.java

License:Apache License

@Override
public void proceed() {
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_SUPER,
            RSymbols.R_STYLEABLES_CLASS_NAME, null, "java/lang/Object", null);
    for (String name : symbols.getStyleables().keySet()) {
        writer.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, name, "[I", null, null);
    }/* ww w. java  2s.  c  o  m*/

    writeClinit(writer);
    writer.visitEnd();
    byte[] bytes = writer.toByteArray();
    try {
        if (!dir.isDirectory() && !dir.mkdirs()) {
            throw new RuntimeException("Cannot mkdir " + dir);
        }
        Files.write(dir.toPath().resolve(RSymbols.R_STYLEABLES_CLASS_NAME + ".class"), bytes);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Create or get a MessageCaller implementation for the given method.
 * @param ownerClass the class that owns the message
 * @param method the method to invoke/*from  www  . ja  va2 s  .c o m*/
 * @return the message caller
 * @throws NoSuchMethodException 
 * @throws SecurityException 
 */
@SuppressWarnings("unchecked")
public static Class<MessageCaller<?>> createMessageCaller(Class<?> ownerClass, Method method)
        throws SecurityException, NoSuchMethodException {

    String className = String.format("%s_%s_%d__MESSAGECALLER", ownerClass.getName(), method.getName(),
            getMethodNumber(method));
    String classNameInternal = className.replace('.', '/');
    java.lang.reflect.Type fullReturnType = method.getGenericReturnType();
    if ((!(fullReturnType instanceof ParameterizedType))
            && AsyncResult.class.isAssignableFrom(((Class) ((ParameterizedType) fullReturnType).getRawType())))
        throw new RuntimeException("Something's wrong here: should not be called for such a method");
    String returnSignature = GenericTypeHelper
            .getSignature(((ParameterizedType) fullReturnType).getActualTypeArguments()[0]);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;

    cw.visit(codeVersion, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER + Opcodes.ACC_SYNTHETIC,
            classNameInternal, "L" + classNameInternal + "<" + returnSignature + ">;",
            "org/actorsguildframework/internal/MessageCaller", null);
    cw.visitSource(null, null);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/actorsguildframework/internal/MessageCaller", "<init>",
                "()V");
        mv.visitInsn(Opcodes.RETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke",
                "(Lorg/actorsguildframework/Actor;[Ljava/lang/Object;)Lorg/actorsguildframework/AsyncResult;",
                "(Lorg/actorsguildframework/Actor;[Ljava/lang/Object;)Lorg/actorsguildframework/AsyncResult<"
                        + returnSignature + ">;",
                null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);

        mv.visitVarInsn(Opcodes.ALOAD, 1);
        mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(method.getDeclaringClass()) + "__ACTORPROXY");

        int idx = 0;
        for (Class<?> t : method.getParameterTypes()) {
            mv.visitVarInsn(Opcodes.ALOAD, 2);
            mv.visitIntInsn(Opcodes.BIPUSH, idx);
            mv.visitInsn(Opcodes.AALOAD);
            if (t.isPrimitive()) {
                String wrapperDescr = GenerationUtils.getWrapperInternalName(t);
                mv.visitTypeInsn(Opcodes.CHECKCAST, wrapperDescr);
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, wrapperDescr, t.getName() + "Value",
                        "()" + Type.getDescriptor(t));
            } else {
                if (isArgumentFreezingRequired(method, idx, t)) {
                    mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(SerializableFreezer.class));
                    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(SerializableFreezer.class),
                            "get", Type.getMethodDescriptor(SerializableFreezer.class.getMethod("get")));
                }
                if (!t.equals(Object.class))
                    mv.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(t));
            }
            idx++;
        }
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
                Type.getInternalName(method.getDeclaringClass()) + "__ACTORPROXY",
                String.format(SUPER_CALLER_NAME_FORMAT, method.getName()), Type.getMethodDescriptor(method));

        mv.visitInsn(Opcodes.ARETURN);

        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l2, 0);
        mv.visitLocalVariable("instance", "Lorg/actorsguildframework/Actor;", null, l0, l2, 1);
        mv.visitLocalVariable("arguments", "[Ljava/lang/Object;", null, l0, l2, 2);

        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getMessageName", "()Ljava/lang/String;", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLdcInsn(method.getName());
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + classNameInternal + ";", null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    cw.visitEnd();

    return (Class<MessageCaller<?>>) GenerationUtils.loadClass(className, cw.toByteArray());
}

From source file:org.actorsguildframework.internal.codegenerator.ActorProxyCreator.java

License:Apache License

/**
 * Creates and loads the actor's proxy class.
 * @param actorClass the Actor class//from   w ww .  jav  a 2 s  .c o m
 * @param acd the actor's class descriptor
 * @throws ConfigurationException if the agent is not configured correctly
 */
@SuppressWarnings("unchecked")
private static Class<?> generateProxyClass(Class<?> actorClass, final ActorClassDescriptor acd)
        throws NoSuchMethodException {
    BeanClassDescriptor bcd = acd.getBeanClassDescriptor();

    String className = String.format("%s__ACTORPROXY", actorClass.getName());
    final String classNameInternal = className.replace('.', '/');
    String classNameDescriptor = "L" + classNameInternal + ";";

    final Type actorState = Type
            .getType(acd.getConcurrencyModel().isMultiThreadingCapable() ? MultiThreadedActorState.class
                    : SingleThreadedActorState.class);

    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    MethodVisitor mv;
    cw.visit(codeVersion, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER + Opcodes.ACC_SYNTHETIC,
            classNameInternal, null, Type.getInternalName(actorClass),
            new String[] { "org/actorsguildframework/internal/ActorProxy" });

    cw.visitSource(null, null);

    {
        for (int i = 0; i < acd.getMessageCount(); i++)
            cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_STATIC,
                    String.format(MESSAGE_CALLER_NAME_FORMAT, i),
                    "Lorg/actorsguildframework/internal/MessageCaller;",
                    "Lorg/actorsguildframework/internal/MessageCaller<*>;", null).visitEnd();

        cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, "actorState__ACTORPROXY",
                actorState.getDescriptor(), null, null).visitEnd();
    }

    BeanCreator.writePropFields(bcd, cw);

    {
        mv = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
        mv.visitCode();

        for (int i = 0; i < acd.getMessageCount(); i++) {
            Class<?> caller = createMessageCaller(acd.getMessage(i).getOwnerClass(),
                    acd.getMessage(i).getMethod());
            String mcName = Type.getInternalName(caller);
            mv.visitTypeInsn(Opcodes.NEW, mcName);
            mv.visitInsn(Opcodes.DUP);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, mcName, "<init>", "()V");
            mv.visitFieldInsn(Opcodes.PUTSTATIC, classNameInternal,
                    String.format(MESSAGE_CALLER_NAME_FORMAT, i),
                    "Lorg/actorsguildframework/internal/MessageCaller;");
        }
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    BeanCreator.writeConstructor(actorClass, bcd, classNameInternal, cw, new BeanCreator.SnippetWriter() {
        @Override
        public void write(MethodVisitor mv) {
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitTypeInsn(Opcodes.NEW, actorState.getInternalName());
            mv.visitInsn(Opcodes.DUP);
            mv.visitVarInsn(Opcodes.ALOAD, 1);
            mv.visitVarInsn(Opcodes.ALOAD, 0);
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, actorState.getInternalName(), "<init>",
                    "(Lorg/actorsguildframework/internal/Controller;Lorg/actorsguildframework/Actor;)V");
            mv.visitFieldInsn(Opcodes.PUTFIELD, classNameInternal, "actorState__ACTORPROXY",
                    actorState.getDescriptor());
        }
    });

    BeanCreator.writePropAccessors(bcd, classNameInternal, cw);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getState__ACTORPROXYMETHOD",
                "()Lorg/actorsguildframework/internal/ActorState;", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, classNameInternal, "actorState__ACTORPROXY",
                actorState.getDescriptor());
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    for (int i = 0; i < acd.getMessageCount(); i++) {
        MessageImplDescriptor mid = acd.getMessage(i);
        Method method = mid.getMethod();
        String simpleDescriptor = Type.getMethodDescriptor(method);
        String genericSignature = GenericTypeHelper.getSignature(method);

        writeProxyMethod(classNameInternal, classNameDescriptor, cw, i, actorState, acd.getConcurrencyModel(),
                mid, method, simpleDescriptor, genericSignature);

        writeSuperProxyMethod(actorClass, classNameDescriptor, cw, method, simpleDescriptor, genericSignature,
                !acd.getConcurrencyModel().isMultiThreadingCapable());
    }

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_SYNCHRONIZED, "toString", "()Ljava/lang/String;",
                null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "toString", "()Ljava/lang/String;");
        mv.visitInsn(Opcodes.ARETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", classNameDescriptor, null, l0, l1, 0);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }
    cw.visitEnd();

    try {
        return (Class<? extends ActorProxy>) GenerationUtils.loadClass(className, cw.toByteArray());
    } catch (Exception e) {
        throw new ConfigurationException("Failure loading ActorProxy", e);
    }
}