From a342f844b8602a3c4db76daa820690f6040a868f Mon Sep 17 00:00:00 2001 From: Kerooker Date: Wed, 26 Dec 2018 18:24:10 -0200 Subject: [PATCH] Implements `KAnnotatedElement.hasAnnotation()` This commit fixes KT-29041, by adding a convenience method to verify if a certain `KAnnotatedElement` has an annotation or not --- .../reflection/annotations/hasAnnotation.kt | 25 +++++++++++++++++++ .../kotlin/reflect/full/KAnnotatedElements.kt | 7 ++++++ 2 files changed, 32 insertions(+) create mode 100644 compiler/testData/codegen/box/reflection/annotations/hasAnnotation.kt diff --git a/compiler/testData/codegen/box/reflection/annotations/hasAnnotation.kt b/compiler/testData/codegen/box/reflection/annotations/hasAnnotation.kt new file mode 100644 index 00000000000..c46cf570849 --- /dev/null +++ b/compiler/testData/codegen/box/reflection/annotations/hasAnnotation.kt @@ -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()) + assertFalse(Bar::class.hasAnnotation()) + + assertTrue(Foo::class.hasAnnotation()) + assertTrue(Foo::class.hasAnnotation()) + + return "OK" +} diff --git a/core/reflection.jvm/src/kotlin/reflect/full/KAnnotatedElements.kt b/core/reflection.jvm/src/kotlin/reflect/full/KAnnotatedElements.kt index 2b869b7c66f..5e16e718b73 100644 --- a/core/reflection.jvm/src/kotlin/reflect/full/KAnnotatedElements.kt +++ b/core/reflection.jvm/src/kotlin/reflect/full/KAnnotatedElements.kt @@ -26,3 +26,10 @@ import kotlin.reflect.* inline fun 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 KAnnotatedElement.hasAnnotation(): Boolean = + findAnnotation() != null \ No newline at end of file