lundi 23 décembre 2019

How to get nullability of Java types using Kotlin reflection?

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





Aucun commentaire:

Enregistrer un commentaire