首页 文章

是否可以让ProGuard使用RetentionPolicy.SOURCE保留元素?

提问于
浏览
1

我正在使用位于Android Support Annotations库中的 @VisibleForTesting 注释,它看起来像这样:

@Retention(SOURCE)
public @interface VisibleForTesting {
}

据我了解,ProGuard对.class文件进行操作,由于其保留策略,由于此注释在编译时不可用,因此所有带注释的方法都将被删除 . 我想在我的应用程序上运行自动化测试,并使用公开的方法进行测试,以验证ProGuard配置不会破坏任何用例 .

是否可以配置ProGuard以某种方式保留这些元素?到目前为止,我已经尝试过:

-keep @android.support.annotation.VisibleForTesting class *
-keep class android.support.annotation.** {
    @**.VisibleForTesting *;
}
-keep interface android.support.annotation.** {
    @**.VisibleForTesting *;
}

和:

-keep interface android.support.annotation.VisibleForTesting

-keepclasseswithmembers class * {
    @android.support.annotation.VisibleForTesting *;
}

-keepclassmembers class ** {
    @android.support.annotation.VisibleForTesting *;
}

这两种配置不起作用 . 如果我也使用 @Keep 注释方法,并配置ProGuard以保留这些方法,则保留方法并通过测试 . 但是,通过这样做,我必须使用两个注释注释所有方法 .

是否可以挂钩注释处理器并覆盖 @VisibleForTesting 的保留策略?或者在构建过程中已经太晚了?

Guava的 @VisibleForTesting 使用 RetentionPolicy.CLASS ,而Android支持注释库使用 RetentionPolicy.SOURCE . 我'm considering posting a request to change the policy, but I suppose it'设置为 SOURCE 有一个原因,可能是由于性能和文件大小略有增加?

除了使用两个注释( @VisibleForTesting@Keep )之外还有其他选项吗?

1 回答

  • 2

    带有 RetentionPolicy == SOURCE 的注释不存在于ProGuard运行的.class文件中 . 因此,没有办法在规则中使用它们,因为它们永远不会匹配 .

    使用 RetentionPolicy == CLASS 的注释应该可以正常工作 . 如果需要,甚至可以使用ProGuard在发布版本中删除它们 .

相关问题