Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin custom annotation, arguments

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?

like image 875
Rens Avatar asked Mar 06 '18 19:03

Rens


People also ask

How do you make custom annotations on Kotlin?

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.

How do you inherit annotations?

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.

What is a type annotation in Kotlin?

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.

How do you know if a class is annotated?

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.


1 Answers

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.

like image 125
Oliver Charlesworth Avatar answered Nov 15 '22 04:11

Oliver Charlesworth