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.

Manfred Moser
  • 29,539
  • 13
  • 92
  • 123

2 Answers2

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 *
Eric Lafortune
  • 45,150
  • 8
  • 114
  • 106
  • 8
    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. – Snicolas Jun 07 '13 at 08:50
  • 3
    I had to also add keepclassmembers. But you gave a good idea, so +1 – Display Name May 09 '15 at 22:23
  • 2
    Also if you use custom Annotations make sure the RetentionPolicy is CLASS or RUNTIME, otherwise proguard will not be able to find them. – Someone Mar 10 '17 at 13:14
20

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 *;
}
Sahil Jain
  • 629
  • 7
  • 12
  • 5
    Hi, for those who find this answer applicable to their cases, there is a predefined annotation @androidx.annotation.Keep – Inliner Dec 09 '20 at 10:40
  • 1
    @Inliner The Keep annotation refers to keeping the class from being removed during minify if it's not accessed – Didi Apr 05 '21 at 14:50
  • @Didi 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. https://medium.com/androiddevelopers/practical-proguard-rules-examples-5640a3907dc9 Also you can look at predefined proguard rules by Android Studio and see how to create your own annotation. – Inliner Apr 06 '21 at 21:37