5

I have two types of annotation in my project: Annotation1 and Annotation2. Both are runtime annotations. So, my question is how to keep only Annotation1 and strip Annotation2?

Example:

class Test {
    @Annotation1
    @Annotation2
    String name;
}

I want Annotation2 to be removed from all fields and Annotation1 to be kept everywhere.

I can't find whether this is possible. I only know how to keep all annotations using:

-keepattributes *Annotation*

Is this possible? If not, why?

2 Answers 2

2

ProGuard automatically removes annotations from the classes/fields/methods if the corresponding annotation classes are not used (retrieved, cast, invoked,...) elsewhere. You can't force ProGuard to remove annotations, but you can tell it to keep seemingly unused annotations:

-keep @interface com.example.MyAnnotation
1
  • 2
    This question isn't about keeping the annotation classes, it's about keeping them applied where they are used. Oct 11, 2021 at 8:17
2

I was looking for the same, but after considering the documentation at great length, and related questions on Stack Overflow, my conclusion is this is not supported.

At the time of writing, only the following options related to annotations can be passed to -keepattributes. For runtime visible annotations:

  • RuntimeVisibleAnnotations: keep all annotations on classes, fields, and methods
  • RuntimeVisibleParameterAnnotations: keep all annotations on method parameters
  • RuntimeVisibleTypeAnnotations: keep all annotations on generic types, instructions, etc. (not certain what ".etc" is supposed to mean here)

Matching selections for runtime invisible annotations are: RuntimeInvisibleAnnotations, RuntimeInvisibleParameterAnnotations, and RuntimeInvisibleTypeAnnotations. I couldn't find any use case for retaining these.

Lastly AnnotationDefault retains annotation default values.

In my opinion, the wildcard options for -keepattributes (? and *) do more harm than good. They are easily misinterpreted (like I originally did, and others do, and you seem to desire) as a way to specify specific annotations, but this is not the case.

The common -keepattributes *Annotation* option simply selects all of the options listed above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.