【问题标题】:Post-compilation removal of annotations from byte code编译后从字节码中删除注释
【发布时间】:2012-06-20 23:55:30
【问题描述】:

我们正在使用一个包含带有 JAXB 注释的 bean 的库。我们使用这些类的方式不依赖于 JAXB。换句话说,我们不需要 JAXB,也不依赖注解。

但是,由于注释存在,它们最终会被处理注释的其他类引用。这需要我在我们的应用程序中捆绑 JAXB,这是不允许的,因为 JAXB 在 javax.* 包中(android 不允许在您的应用程序中包含“核心库”)。

因此,考虑到这一点,我正在寻找一种从编译字节码中删除注释的方法。我知道有用于操作字节码的实用程序,但这对我来说很新。任何帮助开始实现这一目标将不胜感激。

【问题讨论】:

  • 还有哪些类引用它们?为什么你的 Android 应用中包含这些类?
  • 不幸的是,我无法控制引用注释的类。它们是从另一个库中引用的。
  • 我还是很好奇,引用这些类的库是什么?
  • 杰克逊。任何迭代类注解的类都会导致同样的问题。

标签: java android annotations javassist bcel


【解决方案1】:

我推荐 BCEL 6。你也可以使用 ASM,但我听说 BCEL 更容易使用。下面是一个快速的测试方法,可以让一个字段最终化:

public static void main(String[] args) throws Exception {
    System.out.println(F.class.getField("a").getModifiers());
    JavaClass aClass = Repository.lookupClass(F.class);
    ClassGen aGen = new ClassGen(aClass);
    for (Field field : aGen.getFields()) {
        if (field.getName().equals("a")) {
            int mods = field.getModifiers();
            field.setModifiers(mods | Modifier.FINAL);
        }
    }
    final byte[] classBytes = aGen.getJavaClass().getBytes();
    ClassLoader cl = new ClassLoader(null) {
        @Override
        protected synchronized Class<?> findClass(String name) throws ClassNotFoundException {
            return defineClass("F", classBytes, 0, classBytes.length);
        }
    };
    Class<?> fWithoutDeprecated = cl.loadClass("F");
    System.out.println(fWithoutDeprecated.getField("a").getModifiers());
}

当然,您实际上会将您的类作为文件写入磁盘,然后将它们打包,但这更容易尝试。我手边没有 BCEL 6,所以我不能修改这个例子来删除注释,但我想代码会是这样的:

public static void main(String[] args) throws Exception {
    ...
    ClassGen aGen = new ClassGen(aClass);
    aGen.setAttributes(cleanupAttributes(aGen.getAttributes()));
    aGen.getFields();
    for (Field field : aGen.getFields()) {
        field.setAttributes(cleanupAttributes(field.getAttributes()));
    }
    for (Method method : aGen.getMethods()) {
        method.setAttributes(cleanupAttributes(method.getAttributes()));
    }
    ...
}

private Attribute[] cleanupAttributes(Attribute[] attributes) {
    for (Attribute attribute : attributes) {
        if (attribute instanceof Annotations) {
            Annotations annotations = (Annotations) attribute;
            if (annotations.isRuntimeVisible()) {
                AnnotationEntry[] entries = annotations.getAnnotationEntries();
                List<AnnotationEntry> newEntries = new ArrayList<AnnotationEntry>();
                for (AnnotationEntry entry : entries) {
                    if (!entry.getAnnotationType().startsWith("javax")) {
                        newEntries.add(entry);
                    }
                }
                annotations.setAnnotationTable(newEntries);
            }
        }
    }
    return attributes;
}

【讨论】:

  • 对于任何尝试这样做的人 - 我还必须修改“ConstantPool”(即使从属性中删除它也包含注释)。可能是我做错了什么,但它现在对我有用。
【解决方案2】:

我使用ByteBuddy 库来删除注释。不幸的是,我无法使用高级 api 删除注释,所以我使用了 ASM api。这是一个示例,如何从类的字段中删除 @Deprecated 注释:

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.jar.asm.AnnotationVisitor;
import net.bytebuddy.jar.asm.FieldVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.jar.asm.Type;
import net.bytebuddy.matcher.ElementMatchers;

import java.lang.annotation.Annotation;
import java.util.Arrays;

public class Test {

    public static class Foo {
        @Deprecated
        public Integer bar;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("Annotations before processing " + getAnnotationsString(Foo.class));
        Class<? extends Foo> modifiedClass = new ByteBuddy()
                .redefine(Foo.class)
                .visit(new AsmVisitorWrapper.ForDeclaredFields()
                        .field(ElementMatchers.isAnnotatedWith(Deprecated.class),
                                new AsmVisitorWrapper.ForDeclaredFields.FieldVisitorWrapper() {
                                    @Override
                                    public FieldVisitor wrap(TypeDescription instrumentedType,
                                                             FieldDescription.InDefinedShape fieldDescription,
                                                             FieldVisitor fieldVisitor) {
                                        return new FieldVisitor(Opcodes.ASM5, fieldVisitor) {
                                            @Override
                                            public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                                                if (Type.getDescriptor(Deprecated.class).equals(desc)) {
                                                    return null;
                                                }
                                                return super.visitAnnotation(desc, visible);
                                            }
                                        };
                                    }
                                }))
                // can't use the same name, because Test$Foo is already loaded
                .name("Test$Foo1")
                .make()
                .load(Test.class.getClassLoader())
                .getLoaded();
        System.out.println("Annotations after processing " + getAnnotationsString(modifiedClass));
    }

    private static String getAnnotationsString(Class<? extends  Foo> clazz) throws NoSuchFieldException {
        Annotation[] annotations = clazz.getDeclaredField("bar").getDeclaredAnnotations();
        return Arrays.toString(annotations);
    }
}

【讨论】:

    【解决方案3】:

    除了混淆您的代码之外,ProGuard 也会这样做。

    【讨论】:

    • 谢谢。是的,但是让 proguard 针对广泛而多样的依赖项运行本身就是一个项目。我正在寻找更快的解决方案(如果存在的话)。
    • 如何使用 ProGuard 做到这一点?我看到一个可用于注释的-keepattributes 选项,但没有看到太多关于删除的内容。
    【解决方案4】:

    还有一个额外的 AntTask Purge Annotation References Ant Task,它

    从 java 字节码/类文件中清除对注解的引用 (从带注释的元素中删除 @Anno 标记)。现在你可以使用 编译后检查字节码中的星座的注释,但是 在释放 jar 之前删除使用过的 annos。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 2011-05-23
      • 2015-01-09
      • 1970-01-01
      相关资源
      最近更新 更多