Implements KAnnotatedElement.hasAnnotation()

This commit fixes KT-29041, by adding a convenience method to verify if a certain `KAnnotatedElement` has an annotation or not
This commit is contained in:
Kerooker
2018-12-26 18:24:10 -02:00
committed by Alexander Udalov
parent 3a33f68fc9
commit a342f844b8
2 changed files with 32 additions and 0 deletions
@@ -0,0 +1,25 @@
// TARGET_BACKEND: JVM
// WITH_REFLECT
import kotlin.reflect.full.hasAnnotation
import kotlin.test.assertFalse
import kotlin.test.assertTrue
annotation class Baz
annotation class Far
@Baz
@Far
class Foo
class Bar
fun box(): String {
assertFalse(Bar::class.hasAnnotation<Baz>())
assertFalse(Bar::class.hasAnnotation<Far>())
assertTrue(Foo::class.hasAnnotation<Baz>())
assertTrue(Foo::class.hasAnnotation<Far>())
return "OK"
}
@@ -26,3 +26,10 @@ import kotlin.reflect.*
inline fun <reified T : Annotation> KAnnotatedElement.findAnnotation(): T? =
@Suppress("UNCHECKED_CAST")
annotations.firstOrNull { it is T } as T?
/**
* Returns true if this element is annotated with [T], false otherwise
*/
@SinceKotlin("1.4")
inline fun <reified T : Annotation> KAnnotatedElement.hasAnnotation(): Boolean =
findAnnotation<T>() != null