Keep annotated class in Proguard
Asked Answered
S

2

36

I have a bunch of classes that use e.g. an @Singleton annotation like so

@Singleton
public class ImageCache

that I would like to keep. How can I configure a proguard -keep statement so it applies to all classes that have that annotation.

Btw in terms of context I need this for an app using Roboguice on Android, which is why I added the tags. Might help others.

Squirrel answered 23/7, 2012 at 23:52 Comment(0)
B
56

ProGuard is based on a java-like configuration with wild-cards. It does require fully qualified class names. This should work:

-keep @com.google.inject.Singleton public class *
Bucher answered 24/7, 2012 at 23:12 Comment(3)
This one is a piece of gold. It's damn usefull to keep jackson 1, jackson 2 and gson annotated classes. ;) Eric, I believe proguard manual should be more explicit about keeping annotated classes, methods, fields, etc.Diploma
I had to also add keepclassmembers. But you gave a good idea, so +1Glynnis
Also if you use custom Annotations make sure the RetentionPolicy is CLASS or RUNTIME, otherwise proguard will not be able to find them.Defoe
W
21

First define an annotation

public @interface DoNotStrip {}

Then put this in proguard.cfg:

-keep,allowobfuscation @interface com.something.DoNotStrip

# Do not strip any method/class that is annotated with @DoNotStrip
-keep @com.something.DoNotStrip class *
-keepclassmembers class * {
    @com.something.DoNotStrip *;
}
Written answered 10/9, 2017 at 20:5 Comment(3)
Hi, for those who find this answer applicable to their cases, there is a predefined annotation @androidx.annotation.KeepEliga
@Eliga The Keep annotation refers to keeping the class from being removed during minify if it's not accessedInaccuracy
@Inaccuracy Thank you, it is indeed true. The same as the proguard rule. The difference is in the number of tweaks available when you are using them. In the following article, there is a description of when to use each of them. medium.com/androiddevelopers/… Also you can look at predefined proguard rules by Android Studio and see how to create your own annotation.Eliga

© 2022 - 2024 — McMap. All rights reserved.