I'm trying to create a custom annotation with an array of arguments but I get an error when trying to set the arguments in the constructor of the annotation. It says it is expecting a type annotation on the Role[], while, if i'm right the Role[] is the type. I looked up the syntax in the docs which can be found here: https://kotlinlang.org/docs/reference/annotations.html. But this documentation only explains how I can use the annotation and not how to create one.
This is what my annotation code looks like:
@NameBinding
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Secured(vararg val value: Role[])
This is what my Role class looks like:
enum class Role {
ADMIN, USER
}
and this is how I want to use it:
@Secured(Role.ADMIN, Role.USER)
I tried looking for any examples on how to create annotations in Kotlin but I can't seem to find any weirdly. Anyone who can help me out?
In order to declare an annotation, we define a class and place the annotation keyword before the class one. By their nature, declarations of annotation cannot contain any code. When we declare our custom annotations, we should specify to which code elements they might apply and where they should be stored.
Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it.
The core concept in Kotlin is the same. An annotation allows you to associate additional metadata with a declaration. The metadata can then be accessed by tools that work with source code, with compiled class files, or at runtime, depending on how the annotation is configured.
The isAnnotation() method is used to check whether a class object is an annotation. The isAnnotation() method has no parameters and returns a boolean value. If the return value is true , then the class object is an annotation.
The following compiles:
enum class Role { ADMIN, USER }
annotation class Secured(vararg val value: Role)
@Secured(Role.ADMIN, Role.USER)
fun foo() {}
As does this:
enum class Role { ADMIN, USER }
annotation class Secured(val value: Array<Role>)
@Secured([Role.ADMIN, Role.USER])
fun foo() {}
They compile to the same bytecode, but Kotlin demands that you use slightly different syntax to instantiate the annotation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With