4

When I use Kotlin reflection to get nullability of Kotlin properties like val nullableString: String? I get correct information in isMarkedNullable property of KType. It also works "inside" types like val nullableList: List<String?>? where not only whole list is nullable but also individual elements can be null.

I would like to use the same mechanism also for Java types. It partially works, for example when I have property like public @javax.annotation.Nullable String text;. But @javax.annotation.Nullable cannot be used like this public List<@Nullable String> list; because it doesn't have TYPE_USE target. So I would like to use @org.checkerframework.checker.nullness.qual.Nullable but this annotation is ignored by Kotlin reflection.

Here is some test:

public class KotlinReflectionTest {

    public static void main(String[] args) {
        for (Field field : TestClass.class.getFields()) {
            final KProperty<?> kProperty = ReflectJvmMapping.getKotlinProperty(field);
            System.out.println(kProperty.getName() + " nullable: " + kProperty.getReturnType().isMarkedNullable());
        }
    }

    public static class TestClass {
        public String text;                                                              // false
        public @javax.annotation.Nullable String textJavax;                              // true
        public @org.jetbrains.annotations.Nullable String textJetbrains;                 // false
        public @org.checkerframework.checker.nullness.qual.Nullable String textChecker;  // false
    }

}

which produces following output:

text nullable: false
textJavax nullable: true
textJetbrains nullable: false
textChecker nullable: false

Is it possible to tell Kotlin reflection which annotations to use? Do they plan to support Checker Framework? I would appreciate any comment. Thanks

Vojta
  • 1,583
  • 17
  • 19
  • 1
    The CheckerFramework annotations should already be supported. This [page in the docs](https://kotlinlang.org/docs/reference/java-interop.html#nullability-annotations) says that the full list can be found in the compiler sources, and here they are: [(link)](https://github.com/JetBrains/kotlin/blob/master/core/descriptors.jvm/src/org/jetbrains/kotlin/load/java/JvmAnnotationNames.kt) – hotkey Dec 23 '19 at 10:58
  • I saw this list of annotations supported by Kotlin compiler. That's why I was hoping that is should also work in reflections. Unfortunately it seems that Kotlin reflections work differently from Kotlin compiler. – Vojta Dec 23 '19 at 11:29
  • `isMarkedNullable` supports only [runtime-retained nullability annotation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-type/is-marked-nullable.html). So, reflection-aware annotations should have `@Retention(RetentionPolicy.RUNTIME)`. – sumio May 07 '20 at 11:14

0 Answers0