简体   繁体   中英

Compile time check if parameter is annotated using Kotlin

I have a requirement in my Android project where I need to validate an argument's annotation. For eg in below function, I need to ensure if block has the required annotation otherwise throw compilation error or lint error

fun doSomething(block : () -> Unit){}
  1. Is there some annotation processing that could help me here
  2. Or can lint check help me

Thank you.

To keep your code cleaner I would suggest to use lint checks, however there is a way to achieve this programatically.

You can use reflection on parameters.

val isAnnotated: Boolean = block::check.hasAnnotation<SomeAnnotation>()

if (!isAnnotated) throw Exception()

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