简体   繁体   中英

Annotation Processing: how to change annotation target in Kotlin code?

Quite often, when I use annotations from Java libraries in Kotlin code, I have to specify target in order to specify what element in the compilled code has to be annotated:

data class User(
    val id: String,

    @get:Email
    val email: String
)

Instead of specifying @get:Email , I would love to be able to use simply @Email , especially if it occurs in many places.

Question: Is there a way to hint Kotlin compiler to use a different target in all places so that if I use @Email it will handle it as if it was @get:Email ? Or is there any other way to omit specifying target? How can it be achieved? May it be done on the compilation stage via annotation processing (like Lombok does)?

I would appreciate any ideas even if they don't answer my question directly.

You can't override it. Maybe create annotation that will target @Email annotation and provide the property getter when it tries to call target.

Specifying target is dictated by the annotation target. When the target of the annotation is specified to jvm use-targets then you must use @get: to specify that the annotation targets the getter of the property.

In order to use simply @Email you must use kotlin target types for your annotation, probably PROPERTY . Note that, PROPERTY target doesn't work with Java.

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
annotation class Email

It should be possible with Kotlin Compiler plugins API. It's a complicated way, tho.

To achieve this you will need to add a ClassBuilder interceptor with a visitor handling @Email annotation and specifying a correct target.

Can't say without getting deeper if visitor will be enough or you will also need to modify source code on one of the compiler stages, check TreeVisitor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM