user4003256
user4003256

Reputation:

Proguard, how to keep constructor that it's parameters has some annotations?

If parameters has my custom annotation(s), then the constructor should be keep.

Upvotes: 0

Views: 1245

Answers (1)

user4003256
user4003256

Reputation:

Well, solved by myself using annotation processor.

Create an annotation that applied to class which should keep constructor:

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.BINARY)
annotation class KeepInit

Annotation processor for project building:

fun enclosingType(el: Element): Element {
    var e: Element? = el
    var c: TypeElement?
    do {
        e = e?.enclosingElement
        c = e as? TypeElement
    } while (e != null && c == null)
    return c ?: el
}


val enclosing = enclosingType(elementOfCustomAnnotation)
if (enclosing.annotationMirrors.none { it.annotationType.toString() == "xxx.foo.bar.KeepInit" }) {
    throw Exception("must add @KeepInit to class: $enclosing")
}

Proguard rule:

-keepclassmembers,allowobfuscation @xxx.foo.bar.KeepInit class * {
    <init>(...);
}

Example:

@KeepInit
class SomeClass(
    @SomeCustomAnnotation("id") private val id: String,
    @SomeCustomAnnotation("title") private val title: String
)

Upvotes: 1

Related Questions