How to save classes containing specific members?

I want to save only classes containing methods annotated with @Keep and these methods. These methods (and class ownership) must be preserved even if they are not used.

What I write in a .pro file:

 -keepclassmembers class * { @Keep *; } -keepclasseswithmembers class * { @Keep *; } 

But it compresses classes using @Keep methods if they are not used.

Then I try this:

 -keep class * { @Keep *; } 

it just saves all the classes.

So what should I write in a .pro file?

Update 1: Example Thank you for your reply. But I already use fully qualified annotation names and include JAR with annotations, but I do not do what I want. So, I prepared a sample.

I have 2 JARs:

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 configuration, 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 *; } 

Look, the package names are correct and all JARs are included.

The resulting map file:

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

So A.class is deleted. What am I doing wrong?

+6
source share
1 answer

As in the examples / annotations / lib / annotations.pro in the ProGuard distribution, you must specify fully qualified names. In addition, the -keepclasseswithmembers option does not work well with the wildcard character "*" - use "<methods>"; instead of this:

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

You should also remember to read a jar containing annotation classes:

 -libraryjars annotations.jar 
+15
source

Source: https://habr.com/ru/post/891816/


All Articles