非空类型抛出 KotlinNullPointerException。

huangapple 未分类评论43阅读模式
英文:

Non nullable type throwing KotlinNullPointerException

问题

我在Java中有以下的类

    public class MyZClass1_ {
    
        public int x = 100;
    
    }

然后在Kotlin中对它进行了测试

    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    class _01_SO_KotlinReflectionAccessorReturnTypeKotlinNull {
    
        @Test
        fun demonstrate_returnTypeReflectionOfAccessorFunctionInJavaClassThrowsKotlinNull() {
            val zClass1_ = MyZClass1_::class
            for (declaredProperty in zClass1_.declaredMemberProperties) {
                val propertyGetter = declaredProperty.getter
                assertNotNull(propertyGetter)
                try {
                    val returnType = propertyGetter.returnType
                } catch (ex: KotlinNullPointerException) {
                    ex.printStackTrace()
                }
            }
        }
    
    }

 - `propertyGetter` 不为 null如断言所示
 - `propertyGetter.returnType` 有一个非空类型 `KType`
 - 问题是这一行 `val returnType = propertyGetter.returnType` 抛出了 `KotlinNullPointerException`。
 - 为什么会这样我是否漏掉了什么
英文:

I have the following class in java

public class MyZClass1_ {

    public int x = 100;

}

and that test in kotlin

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class _01_SO_KotlinReflectionAccessorReturnTypeKotlinNull {

    @Test
    fun demonstrate_returnTypeReflectionOfAccessorFunctionInJavaClassThrowsKotlinNull() {
        val zClass1_ = MyZClass1_::class
        for (declaredProperty in zClass1_.declaredMemberProperties) {
            val propertyGetter = declaredProperty.getter
            assertNotNull(propertyGetter)
            try {
                val returnType = propertyGetter.returnType
            } catch (ex: KotlinNullPointerException) {
                ex.printStackTrace()
            }
        }
    }

}
  • propertyGetter is not null (as asserted)
  • propertyGetter.returnType has a non-nullable type KType
  • The problem is that the line val returnType = propertyGetter.returnType throws a KotlinNullPointerException.
  • Why is that? Am i missing something?

huangapple
  • 本文由 发表于 2020年4月3日 22:57:07
  • 转载请务必保留本文链接:https://java.coder-hub.com/61014647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定