Search code examples
javamavenproguard

Using ProGuard, keep class fields with wildcard


I'd like to keep certain class fields untouched by ProGuard if the field name starts with a certain string. Currently I'm just setting all fields to be kept, but would like to refine that to keep all public & protected fields, and only the private fields that start with this string.

This is the current config in my pom.xml:

<option>-keepclassmembers class com.my.package.** { &lt;fields&gt;; }</option>

I have tried the following, and similar variants:

<option>-keepclassmembers class com.my.package.** { public *; protected *; private string***; }</option>

But ProGuard throws an error (works fine when I just use "private *;"):

[proguard] Error: Expecting class member name before ';' in argument number 39

I'm guessing I'm either using the wildcard incorrectly, or this can't be done? I have check the usage/examples section of the ProGuard site and other examples through Google, and I see usually the full definition of the field might be needed (private final String stringVariable), but I'm not 100% sure.


Solution

  • The pattern is intended to look like Java, but with wildcards. You can use the following:

    -keepclassmembers class com.my.package.** {
        public protected <fields>;
        private *** string*;
    }
    

    The wildcard <fields> matches all fields (any type, any name), in this case constrained to only match public or protected fields.

    On the next line, the wildcard *** matches any type (including primitive types and array types) and the expression string* matches any name starting with 'string', in this case further constrained to private fields.

    If useful, you could add other constraints to both lines, for example !static to only match non-static fields.