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:co.cask.tigon.internal.io.DatumWriterGenerator.java

License:Apache License

/**
 * Generates a {@link DatumWriter} class for encoding data of the given output type with the given schema.
 * @param outputType Type information of the output data type.
 * @param schema Schema of the output data type.
 * @return A {@link co.cask.tigon.internal.asm.ClassDefinition} that contains generated class information.
 *///  w w w.jav  a 2  s  .c o m
ClassDefinition generate(TypeToken<?> outputType, Schema schema) {
    classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);

    TypeToken<?> interfaceType = getInterfaceType(outputType);

    // Generate the class
    String className = getClassName(interfaceType, schema);
    classType = Type.getObjectType(className);
    classWriter.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, className,
            Signatures.getClassSignature(interfaceType), Type.getInternalName(Object.class),
            new String[] { Type.getInternalName(interfaceType.getRawType()) });

    // Static schema hash field, for verification
    classWriter.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, "SCHEMA_HASH",
            Type.getDescriptor(String.class), null, schema.getSchemaHash().toString()).visitEnd();

    // Schema field
    classWriter.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, "schema", Type.getDescriptor(Schema.class),
            null, null).visitEnd();

    // Encode method
    generateEncode(outputType, schema);

    // Constructor
    generateConstructor();

    ClassDefinition classDefinition = new ClassDefinition(classWriter.toByteArray(), className);
    // DEBUG block. Uncomment for debug
    //    co.cask.tigon.internal.asm.Debugs.debugByteCode(classDefinition, new java.io.PrintWriter(System.out));
    // End DEBUG block
    return classDefinition;
}

From source file:co.cask.tigon.internal.io.FieldAccessorGenerator.java

License:Apache License

ClassDefinition generate(TypeToken<?> classType, Field field, boolean publicOnly) {
    String name = String.format("%s$GeneratedAccessor%s", classType.getRawType().getName(), field.getName());
    if (name.startsWith("java.") || name.startsWith("javax.")) {
        name = "co.cask.tigon." + name;
        publicOnly = true;/*w  w  w. jav  a 2s.  c  om*/
    }
    this.className = name.replace('.', '/');

    if (publicOnly) {
        isPrivate = !Modifier.isPublic(field.getModifiers())
                || !Modifier.isPublic(field.getDeclaringClass().getModifiers());
    } else {
        isPrivate = Modifier.isPrivate(field.getModifiers())
                || Modifier.isPrivate(field.getDeclaringClass().getModifiers());
    }

    // Generate the class
    classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    classWriter.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, className, null,
            Type.getInternalName(AbstractFieldAccessor.class), new String[0]);

    generateConstructor(field);
    generateGetter(field);
    generateSetter(field);

    classWriter.visitEnd();

    ClassDefinition classDefinition = new ClassDefinition(classWriter.toByteArray(), className);
    // DEBUG block. Uncomment for debug
    //    co.cask.tigon.internal.asm.Debugs.debugByteCode(classDefinition, new java.io.PrintWriter(System.out));
    // End DEBUG block
    return classDefinition;
}

From source file:com.alibaba.hotswap.processor.field.holder.FieldHolderVisitor.java

License:Open Source License

private void addFieldHolder() {
    FieldVisitor fv = cv.visitField(Opcodes.ACC_TRANSIENT + Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL,
            HotswapConstants.FIELD_HOLDER, "Ljava/util/concurrent/ConcurrentHashMap;", null, null);
    if (fv != null) {
        fv.visitEnd();//from  w w w.  ja  va 2s  . com
    }
}

From source file:com.alibaba.hotswap.processor.field.holder.FieldHolderVisitor.java

License:Open Source License

private void addStaticFieldHolder() {
    FieldVisitor fv = cv.visitField(/*w  w  w. j  av a 2s. c  o m*/
            Opcodes.ACC_TRANSIENT + Opcodes.ACC_STATIC + Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL,
            HotswapConstants.STATIC_FIELD_HOLDER, "Ljava/util/concurrent/ConcurrentHashMap;", null, null);
    if (fv != null) {
        fv.visitEnd();
    }
}

From source file:com.android.build.gradle.internal.incremental.InstantRunVerifier.java

License:Apache License

@NonNull
private static InstantRunVerifierStatus verifyFields(@NonNull ClassNode originalClass,
        @NonNull ClassNode updatedClass) {

    //noinspection unchecked
    Diff diff = diffList(originalClass.fields, updatedClass.fields, new Comparator<FieldNode>() {

        @Override/*www  . ja v a  2  s  .  co  m*/
        public boolean areEqual(@Nullable FieldNode first, @Nullable FieldNode second) {
            if ((first == null) && (second == null)) {
                return true;
            }
            if (first == null || second == null) {
                return true;
            }
            return first.name.equals(second.name) && first.desc.equals(second.desc)
                    && first.access == second.access && Objects.equal(first.value, second.value);
        }
    });

    if (diff != Diff.NONE) {
        // Detect R$something classes, and report changes in them separately.
        String name = originalClass.name;
        int index = name.lastIndexOf('/');
        if (index != -1 && name.startsWith("R$", index + 1) && (originalClass.access & Opcodes.ACC_PUBLIC) != 0
                && (originalClass.access & Opcodes.ACC_FINAL) != 0 && originalClass.outerClass == null
                && originalClass.interfaces.isEmpty() && originalClass.superName.equals("java/lang/Object")
                && name.length() > 3 && Character.isLowerCase(name.charAt(2))) {
            return R_CLASS_CHANGE;
        }
    }

    switch (diff) {
    case NONE:
        return COMPATIBLE;
    case ADDITION:
        return FIELD_ADDED;
    case REMOVAL:
        return FIELD_REMOVED;
    case CHANGE:
        return FIELD_TYPE_CHANGE;
    default:
        throw new RuntimeException("Unhandled action : " + diff);
    }
}

From source file:com.android.build.gradle.internal.transforms.InstantRunTransform.java

License:Apache License

/**
 * Use asm to generate a concrete subclass of the AppPathLoaderImpl class.
 * It only implements one method :/*w  w  w.  java 2  s .c o m*/
 *      String[] getPatchedClasses();
 *
 * The method is supposed to return the list of classes that were patched in this iteration.
 * This will be used by the InstantRun runtime to load all patched classes and register them
 * as overrides on the original classes.2 class files.
 *
 * @param patchFileContents list of patched class names.
 * @param outputDir output directory where to generate the .class file in.
 */
private static void writePatchFileContents(@NonNull ImmutableList<String> patchFileContents,
        @NonNull File outputDir, long buildId) {

    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, IncrementalVisitor.APP_PATCHES_LOADER_IMPL,
            null, IncrementalVisitor.ABSTRACT_PATCHES_LOADER_IMPL, null);

    // Add the build ID to force the patch file to be repackaged.
    cw.visitField(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, "BUILD_ID", "J", null, buildId);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, IncrementalVisitor.ABSTRACT_PATCHES_LOADER_IMPL, "<init>",
                "()V", false);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getPatchedClasses", "()[Ljava/lang/String;", null, null);
        mv.visitCode();
        mv.visitIntInsn(Opcodes.BIPUSH, patchFileContents.size());
        mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
        for (int index = 0; index < patchFileContents.size(); index++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.BIPUSH, index);
            mv.visitLdcInsn(patchFileContents.get(index));
            mv.visitInsn(Opcodes.AASTORE);
        }
        mv.visitInsn(Opcodes.ARETURN);
        mv.visitMaxs(4, 1);
        mv.visitEnd();
    }
    cw.visitEnd();

    byte[] classBytes = cw.toByteArray();
    File outputFile = new File(outputDir, IncrementalVisitor.APP_PATCHES_LOADER_IMPL + ".class");
    try {
        Files.createParentDirs(outputFile);
        Files.write(classBytes, outputFile);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.android.build.gradle.internal2.incremental.IncrementalSupportVisitor.java

License:Apache License

/**
 * Adds serialVersionUID for the classes that does not define one. Reason for this is that if a
 * class does not define a serialVersionUID value, and is used for serialization, instrumented
 * and non-instrumented class will have different serialVersionUID values, and that will break
 * serialization.// w  w  w .  ja  va2 s .c o m
 */
private void addSerialUidIfMissing() {
    // noinspection unchecked
    for (FieldNode f : (List<FieldNode>) classNode.fields) {
        if (f.name.equals("serialVersionUID")) {
            // We should not generate serial uuid, field already exists. Although it might
            // not be static, final, and long, adding would break the instrumented class.
            return;
        }
    }
    try {
        String className = Type.getObjectType(classNode.name).getClassName();
        Class<?> clazz = Class.forName(className, false, Thread.currentThread().getContextClassLoader());

        ObjectStreamClass objectStreamClass = ObjectStreamClass.lookupAny(clazz);
        long serialUuid = objectStreamClass.getSerialVersionUID();

        // adds the field
        super.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, "serialVersionUID",
                Type.LONG_TYPE.getDescriptor(), null, serialUuid);

    } catch (ClassNotFoundException ex) {
        LOG.verbose("Unable to add auto-generated serialVersionUID for %1$s : %2$s", classNode.name,
                ex.getMessage());
    } catch (LinkageError | AssertionError e) {
        // http://b.android.com/220635 - static initializer might be invoked
        LOG.warning("Unable to generate serialVersionUID for %s. In case you make this class"
                + " serializable and use it to persist data in InstantRun mode, please"
                + " add a serialVersionUID field.", classNode.name);
    }
}

From source file:com.android.builder.testing.MockableJarGenerator.java

License:Apache License

/**
 * Modifies a {@link ClassNode} to clear final flags and rewrite byte code.
 *///from  w  w  w  .  j a v  a  2 s. c o  m
@SuppressWarnings("unchecked")
private void modifyClass(ClassNode classNode) {
    // Make the class not final.
    classNode.access &= ~Opcodes.ACC_FINAL;

    List<MethodNode> methodNodes = classNode.methods;
    for (MethodNode methodNode : methodNodes) {
        methodNode.access &= ~Opcodes.ACC_FINAL;
        fixMethodBody(methodNode, classNode);
    }

    List<FieldNode> fieldNodes = classNode.fields;
    for (FieldNode fieldNode : fieldNodes) {
        // Make public instance fields non-final. This is needed e.g. to "mock" SyncResult.stats.
        if ((fieldNode.access & Opcodes.ACC_PUBLIC) != 0 && (fieldNode.access & Opcodes.ACC_STATIC) == 0) {
            fieldNode.access &= ~Opcodes.ACC_FINAL;
        }
    }

    List<InnerClassNode> innerClasses = classNode.innerClasses;
    for (InnerClassNode innerClassNode : innerClasses) {
        innerClassNode.access &= ~Opcodes.ACC_FINAL;
    }
}

From source file:com.android.ide.eclipse.apt.internal.analysis.ConstantFinalAnalyzer.java

License:Apache License

/**
 * Check if a given field of a class is final or not
 * @param fieldName Field name of a class
 * @return true if the field is final, false otherwise
 *//*w ww .j  a  va2  s.c om*/
@SuppressWarnings("unchecked")
private boolean isFinal(final String fieldName) {
    boolean isFinal = false;
    final List<FieldNode> fields = (List<FieldNode>) mCurrentClass.fields;
    for (final FieldNode fieldNode : fields) {
        if (fieldNode.name.equals(fieldName)) {
            isFinal = (fieldNode.access & Opcodes.ACC_FINAL) != 0;
            break;
        }
    }
    return isFinal;
}

From source file:com.android.mkstubs.sourcer.AccessSourcerTest.java

License:Apache License

@Test
public void testPrivateFinalStatic() throws Exception {
    mSourcer.write(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC, AccessSourcer.IS_METHOD);

    String s = mWriter.toString();
    Assert.assertEquals("private static final", s);
}