【问题标题】:How to keep classes containing specific members?如何保持包含特定成员的类?
【发布时间】:2011-07-01 12:54:07
【问题描述】:

我只想保留类,其中包含用@Keep 注释的方法,以及这些方法。 这些方法(和所属的类)即使未使用也应保留。

我在 .pro-file 中写的是:

-keepclassmembers class * {
    @Keep *;
}

-keepclasseswithmembers class * {
    @Keep *;
}

但是,如果 @Keep 方法未使用,它会缩小类。

然后我试试这个:

-keep class * {
    @Keep *;
}

它只保留所有类。

那么,我应该在 .pro-file 中写什么?

更新 1:示例 感谢您的回答。但是我已经使用了完全限定的注释名称并包含带有注释的 JAR,但它并没有达到我想要的效果。所以,我准备了一个样本。

我有 2 个 JAR:

example.jar/

  example/
    code/
      more/
        A.class

lib.jar/

  example/
    lib/
      Keep.class

A.java

package example.code.more;

import example.lib.*;

public class A {
  @Keep
  void foo() {}
}

Keep.java

package example.lib;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
public @interface Keep {

}

Proguard 配置,example.pro

-injars  example.jar
-injars  lib.jar
-outjars obfuscated.jar

-libraryjars <java.home>/lib/rt.jar

-printmapping rt.map

-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable

-printseeds
-overloadaggressively
-dontoptimize
-keeppackagenames example.lib.**

-keepattributes *Annotation*

-keepclassmembers class * extends java.lang.Enum {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep class example.lib.* { *; }
-keep class * extends java.lang.annotation.Annotation { *; }


-keepclassmembers class * {
    @example.lib.Keep *;
}

-keepclasseswithmembers class * {
    @example.lib.Keep *;
}

看,包名是正确的,所有的 JAR 都包含在内。

生成的地图文件:

example.lib.Keep -> example.lib.Keep:

因此,A.class 被删除。我做错了什么?

【问题讨论】:

    标签: java obfuscation proguard


    【解决方案1】:

    就像在 ProGuard 发行版中的 examples/annotations/lib/annotations.pro 中一样,您应该指定完全限定的名称。此外,选项 -keepclasseswithmembers 不能很好地与“*”通配符结合使用——请改用“”通配符:

    -keepclasseswithmembers class * {
      @proguard.annotation.Keep <methods>;
    }
    

    你也一定不要忘记阅读包含注释类的jar:

    -libraryjars annotations.jar 
    

    【讨论】:

    • 我刚刚用示例更新了该主题。我按照你的建议做了同样的事情,但它仍然不起作用:'(
    • 并将带有注释的 JAR 指定为库 (-libraryjars) 并没有帮助。
    • 更新了解决方案以使用正确的通配符。现在可以使用了。
    • +1 这也适用于自定义注释!
    猜你喜欢
    • 1970-01-01
    • 2014-11-01
    • 2020-11-19
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2014-01-17
    • 2022-12-16
    相关资源
    最近更新 更多