Example usage for org.objectweb.asm Opcodes ACC_FINAL

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

Introduction

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

Prototype

int ACC_FINAL

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

Click Source Link

Usage

From source file:com.google.code.nanorm.internal.introspect.asm.MapperBuilder.java

License:Apache License

/**
 * Build mapper./*w w  w  . j  a  v  a 2s. c om*/
 * 
 * @param name class name
 * @param mapper mapper interface or base class
 * @param configs method configurations
 * @return mapper byte-code
 */
public static byte[] buildMapper(String name, Class<?> mapper, MethodConfig[] configs) {
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);

    Type owner = Type.getType('L' + name + ';');

    if (mapper.isInterface()) {
        cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, name, null, "java/lang/Object",
                new String[] { mapper.getName().replace('.', '/') });
    } else {
        cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, name, null, mapper.getName().replace('.', '/'), null);
    }

    // Copy the annotations
    copyAnnotations(mapper, cw, null);

    cw.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "delegate", QUERY_DELEGATE_TYPE.getDescriptor(),
            null, null);

    cw.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "configs",
            STATEMENT_CONFIGS_ARR_TYPE.getDescriptor(), null, null);

    if (mapper.isInterface()) {
        visitConstructor(cw, owner, OBJECT_TYPE);
    } else {
        visitConstructor(cw, owner, Type.getType(mapper));
    }

    for (MethodConfig cfg : configs) {
        visitMethod(owner, cw, cfg);
    }

    cw.visitEnd();

    return cw.toByteArray();
}

From source file:com.google.devtools.build.android.desugar.LambdaClassFixer.java

License:Open Source License

@Override
public void visitEnd() {
    checkState(!hasState || hasFactory, "Expected factory method for capturing lambda %s", getInternalName());
    if (!hasState) {
        checkState(signature == null, "Didn't expect generic constructor signature %s %s", getInternalName(),
                signature);/*from   www  .j  a  va 2  s  . c o m*/
        checkState(lambdaInfo.factoryMethodDesc().startsWith("()"),
                "Expected 0-arg factory method for %s but found %s", getInternalName(),
                lambdaInfo.factoryMethodDesc());
        // Since this is a stateless class we populate and use a static singleton field "$instance".
        // Field is package-private so we can read it from the class that had the invokedynamic.
        String singletonFieldDesc = lambdaInfo.factoryMethodDesc().substring("()".length());
        super.visitField(Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, SINGLETON_FIELD_NAME, singletonFieldDesc,
                (String) null, (Object) null).visitEnd();

        MethodVisitor codeBuilder = super.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", (String) null,
                new String[0]);
        codeBuilder.visitTypeInsn(Opcodes.NEW, getInternalName());
        codeBuilder.visitInsn(Opcodes.DUP);
        codeBuilder.visitMethodInsn(Opcodes.INVOKESPECIAL, getInternalName(), "<init>",
                checkNotNull(desc, "didn't see a constructor for %s", getInternalName()), /*itf*/ false);
        codeBuilder.visitFieldInsn(Opcodes.PUTSTATIC, getInternalName(), SINGLETON_FIELD_NAME,
                singletonFieldDesc);
        codeBuilder.visitInsn(Opcodes.RETURN);
        codeBuilder.visitMaxs(2, 0); // two values are pushed onto the stack
        codeBuilder.visitEnd();
    }

    copyRewrittenLambdaMethods();
    if (!allowDefaultMethods) {
        copyBridgeMethods(interfaces);
    }
    super.visitEnd();
}

From source file:com.google.devtools.build.android.desugar.LambdaDesugaring.java

License:Open Source License

@Override
public void visitEnd() {
    for (Map.Entry<Handle, MethodReferenceBridgeInfo> bridge : bridgeMethods.entrySet()) {
        Handle original = bridge.getKey();
        Handle neededMethod = bridge.getValue().bridgeMethod();
        checkState(/*from w  w  w . j a va2s .  c  o m*/
                neededMethod.getTag() == Opcodes.H_INVOKESTATIC
                        || neededMethod.getTag() == Opcodes.H_INVOKEVIRTUAL,
                "Cannot generate bridge method %s to reach %s", neededMethod, original);
        checkState(bridge.getValue().referenced() != null, "Need referenced method %s to generate bridge %s",
                original, neededMethod);

        int access = Opcodes.ACC_BRIDGE | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_FINAL;
        if (neededMethod.getTag() == Opcodes.H_INVOKESTATIC) {
            access |= Opcodes.ACC_STATIC;
        }
        MethodVisitor bridgeMethod = super.visitMethod(access, neededMethod.getName(), neededMethod.getDesc(),
                (String) null, toInternalNames(bridge.getValue().referenced().getExceptionTypes()));

        // Bridge is a factory method calling a constructor
        if (original.getTag() == Opcodes.H_NEWINVOKESPECIAL) {
            bridgeMethod.visitTypeInsn(Opcodes.NEW, original.getOwner());
            bridgeMethod.visitInsn(Opcodes.DUP);
        }

        int slot = 0;
        if (neededMethod.getTag() != Opcodes.H_INVOKESTATIC) {
            bridgeMethod.visitVarInsn(Opcodes.ALOAD, slot++);
        }
        Type neededType = Type.getMethodType(neededMethod.getDesc());
        for (Type arg : neededType.getArgumentTypes()) {
            bridgeMethod.visitVarInsn(arg.getOpcode(Opcodes.ILOAD), slot);
            slot += arg.getSize();
        }
        bridgeMethod.visitMethodInsn(invokeOpcode(original), original.getOwner(), original.getName(),
                original.getDesc(), original.isInterface());
        bridgeMethod.visitInsn(neededType.getReturnType().getOpcode(Opcodes.IRETURN));

        bridgeMethod.visitMaxs(0, 0); // rely on class writer to compute these
        bridgeMethod.visitEnd();
    }
    super.visitEnd();
}

From source file:com.google.devtools.build.android.desugar.LambdaDesugaring.java

License:Open Source License

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    if (name.equals("$deserializeLambda$") && BitFlags.isSet(access, Opcodes.ACC_SYNTHETIC)) {
        // Android doesn't do anything special for lambda serialization so drop the special
        // deserialization hook that javac generates.  This also makes sure we don't reference
        // java/lang/invoke/SerializedLambda, which doesn't exist on Android.
        return null;
    }/*www. j  a  va  2 s.c  om*/
    if (name.startsWith("lambda$") && BitFlags.isSet(access, Opcodes.ACC_SYNTHETIC)) {
        if (!allowDefaultMethods && isInterface && BitFlags.isSet(access, Opcodes.ACC_STATIC)) {
            // There must be a lambda in the interface (which in the absence of hand-written default or
            // static interface methods must mean it's in the <clinit> method or inside another lambda).
            // We'll move this method out of this class, so just record and drop it here.
            // (Note lambda body methods have unique names, so we don't need to remember desc here.)
            aggregateInterfaceLambdaMethods.add(internalName + '#' + name);
            return null;
        }
        if (BitFlags.isSet(access, Opcodes.ACC_PRIVATE)) {
            // Make lambda body method accessible from lambda class
            access &= ~Opcodes.ACC_PRIVATE;
            if (allowDefaultMethods && isInterface) {
                // java 8 requires interface methods to have exactly one of ACC_PUBLIC and ACC_PRIVATE
                access |= Opcodes.ACC_PUBLIC;
            } else {
                // Method was private so it can be final, which should help VMs perform dispatch.
                access |= Opcodes.ACC_FINAL;
            }
        }
        // Guarantee unique lambda body method name to avoid accidental overriding. This wouldn't be
        // be necessary for static methods but in visitOuterClass we don't know whether a potential
        // outer lambda$ method is static or not, so we just always do it.
        name = uniqueInPackage(internalName, name);
    }
    MethodVisitor dest = super.visitMethod(access, name, desc, signature, exceptions);
    return dest != null ? new InvokedynamicRewriter(dest, access, name, desc, signature, exceptions) : null;
}

From source file:com.google.devtools.build.android.resources.RClassGenerator.java

License:Open Source License

/**
 * Builds the bytecode and writes out the R.class file, and R$inner.class files.
 *///from  w  w  w  .  java2s . com
public void write() throws IOException {
    Iterable<String> folders = PACKAGE_SPLITTER.split(packageName);
    Path packageDir = outFolder;
    for (String folder : folders) {
        packageDir = packageDir.resolve(folder);
    }
    // At least create the outFolder that was requested. However, if there are no symbols, don't
    // create the R.class and inner class files (no need to have an empty class).
    Files.createDirectories(packageDir);
    if (initializers.isEmpty()) {
        return;
    }
    Path rClassFile = packageDir.resolve(SdkConstants.FN_COMPILED_RESOURCE_CLASS);

    String packageWithSlashes = packageName.replaceAll("\\.", "/");
    String rClassName = packageWithSlashes + "/R";
    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classWriter.visit(JAVA_VERSION, Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SUPER, rClassName,
            null, /* signature */
            SUPER_CLASS, null /* interfaces */);
    classWriter.visitSource(SdkConstants.FN_RESOURCE_CLASS, null);
    writeConstructor(classWriter);

    // Build the R.class w/ the inner classes, then later build the individual R$inner.class.
    for (ResourceType resourceType : initializers.keySet()) {
        String innerClassName = rClassName + "$" + resourceType;
        classWriter.visitInnerClass(innerClassName, rClassName, resourceType.toString(),
                Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC);
    }
    classWriter.visitEnd();
    Files.write(rClassFile, classWriter.toByteArray());

    // Now generate the R$inner.class files.
    for (Map.Entry<ResourceType, List<FieldInitializer>> entry : initializers.entrySet()) {
        writeInnerClass(entry.getValue(), packageDir, rClassName, entry.getKey().toString());
    }
}

From source file:com.google.devtools.build.android.resources.RClassGenerator.java

License:Open Source License

private void writeInnerClass(List<FieldInitializer> initializers, Path packageDir,
        String fullyQualifiedOuterClass, String innerClass) throws IOException {
    ClassWriter innerClassWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String fullyQualifiedInnerClass = writeInnerClassHeader(fullyQualifiedOuterClass, innerClass,
            innerClassWriter);/* ww  w  .j  a  v  a 2 s  .  c o  m*/

    List<FieldInitializer> deferredInitializers = new ArrayList<>();
    int fieldAccessLevel = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC;
    if (finalFields) {
        fieldAccessLevel |= Opcodes.ACC_FINAL;
    }
    for (FieldInitializer init : initializers) {
        if (init.writeFieldDefinition(innerClassWriter, fieldAccessLevel, finalFields)) {
            deferredInitializers.add(init);
        }
    }
    if (!deferredInitializers.isEmpty()) {
        writeStaticClassInit(innerClassWriter, fullyQualifiedInnerClass, deferredInitializers);
    }

    innerClassWriter.visitEnd();
    Path innerFile = packageDir.resolve("R$" + innerClass + ".class");
    Files.write(innerFile, innerClassWriter.toByteArray());
}

From source file:com.google.devtools.build.android.resources.RClassGenerator.java

License:Open Source License

private String writeInnerClassHeader(String fullyQualifiedOuterClass, String innerClass,
        ClassWriter innerClassWriter) {/*from   w  w  w .j av a2  s. com*/
    String fullyQualifiedInnerClass = fullyQualifiedOuterClass + "$" + innerClass;
    innerClassWriter.visit(JAVA_VERSION, Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SUPER,
            fullyQualifiedInnerClass, null, /* signature */
            SUPER_CLASS, null /* interfaces */);
    innerClassWriter.visitSource(SdkConstants.FN_RESOURCE_CLASS, null);
    writeConstructor(innerClassWriter);
    innerClassWriter.visitInnerClass(fullyQualifiedInnerClass, fullyQualifiedOuterClass, innerClass,
            Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC);
    return fullyQualifiedInnerClass;
}

From source file:com.google.devtools.build.android.resources.RClassWriter.java

License:Open Source License

/**
 * Builds the bytecode and writes out the R.class file, and R$inner.class files.
 *//*from w w  w. ja v  a2 s. c o m*/
public void write() throws IOException {
    Splitter splitter = Splitter.on('.');
    Iterable<String> folders = splitter.split(packageName);
    File packageDir = outFolder;
    for (String folder : folders) {
        packageDir = new File(packageDir, folder);
    }
    File rClassFile = new File(packageDir, SdkConstants.FN_COMPILED_RESOURCE_CLASS);
    Files.createParentDirs(rClassFile);
    String packageWithSlashes = packageName.replaceAll("\\.", "/");
    String rClassName = packageWithSlashes + "/R";
    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classWriter.visit(JAVA_VERSION, Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SUPER, rClassName,
            null, SUPER_CLASS, null);
    classWriter.visitSource(SdkConstants.FN_RESOURCE_CLASS, null);
    writeConstructor(classWriter);

    Table<String, String, SymbolEntry> symbols = getAllSymbols();
    Table<String, String, SymbolEntry> values = getSymbols(symbolValues);

    Set<String> rowSet = symbols.rowKeySet();
    List<String> rowList = new ArrayList<>(rowSet);
    Collections.sort(rowList);

    // Build the R.class w/ the inner classes, then later build the individual R$inner.class.
    for (String row : rowList) {
        String innerClassName = rClassName + "$" + row;
        classWriter.visitInnerClass(innerClassName, rClassName, row,
                Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC);
    }
    classWriter.visitEnd();
    Files.write(classWriter.toByteArray(), rClassFile);

    // Now generate the R$inner.class files.
    for (String row : rowList) {
        writeInnerClass(symbols, values, packageDir, rClassName, row);
    }
}

From source file:com.google.devtools.build.android.resources.RClassWriter.java

License:Open Source License

private void writeInnerClass(Table<String, String, SymbolEntry> symbols,
        Table<String, String, SymbolEntry> values, File packageDir, String fullyQualifiedOuterClass,
        String innerClass) throws IOException {
    ClassWriter innerClassWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String fullyQualifiedInnerClass = fullyQualifiedOuterClass + "$" + innerClass;
    innerClassWriter.visit(JAVA_VERSION, Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SUPER,
            fullyQualifiedInnerClass, null, SUPER_CLASS, null);
    innerClassWriter.visitSource("R.java", null);
    writeConstructor(innerClassWriter);//from   w  ww.j  a  va2 s  . c om
    innerClassWriter.visitInnerClass(fullyQualifiedInnerClass, fullyQualifiedOuterClass, innerClass,
            Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC);

    Map<String, SymbolEntry> rowMap = symbols.row(innerClass);
    Set<String> symbolSet = rowMap.keySet();
    List<String> symbolList = new ArrayList<>(symbolSet);
    Collections.sort(symbolList);
    List<DeferredInitializer> deferredInitializers = new ArrayList<>();
    int fieldAccessLevel = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC;
    if (finalFields) {
        fieldAccessLevel |= Opcodes.ACC_FINAL;
    }
    for (String symbolName : symbolList) {
        // get the matching SymbolEntry from the values Table.
        SymbolEntry value = values.get(innerClass, symbolName);
        if (value != null) {
            String desc;
            Object initializer = null;
            if (value.getType().equals("int")) {
                desc = "I";
                if (finalFields) {
                    initializer = Integer.decode(value.getValue());
                } else {
                    deferredInitializers.add(IntDeferredInitializer.of(value.getName(), value.getValue()));
                }
            } else {
                Preconditions.checkArgument(value.getType().equals("int[]"));
                desc = "[I";
                deferredInitializers.add(IntArrayDeferredInitializer.of(value.getName(), value.getValue()));
            }
            innerClassWriter.visitField(fieldAccessLevel, value.getName(), desc, null, initializer).visitEnd();
        }
    }

    if (!deferredInitializers.isEmpty()) {
        // build the <clinit> method.
        writeStaticClassInit(innerClassWriter, fullyQualifiedInnerClass, deferredInitializers);
    }

    innerClassWriter.visitEnd();
    File innerFile = new File(packageDir, "R$" + innerClass + ".class");
    Files.write(innerClassWriter.toByteArray(), innerFile);
}

From source file:com.google.singletondetector.visitors.SingletonClassVisitor.java

License:Apache License

@Override
public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
    if ((access & Opcodes.ACC_STATIC) == Opcodes.ACC_STATIC) {
        if ((access & Opcodes.ACC_PUBLIC) == Opcodes.ACC_PUBLIC) {
            sd.visitStaticField(name, desc);
        }//from   w w  w . j  a va  2 s.c o m

        if ((access & Opcodes.ACC_PRIVATE) == Opcodes.ACC_PRIVATE
                && (access & Opcodes.ACC_FINAL) != Opcodes.ACC_FINAL) {
            sd.addStaticField(name, desc);
        }
    }
    return null;
}