[英]Private String properties are nullable in decompiled .java class Kotlin
When I have a private String property in a Kotlin class and decompile the class into Java code, this property won't have the @NotNull
annotation. 相反,如果我声明一个“公共”字符串属性,它将在反编译代码中具有注释@NotNull
。
这里是一个.kt 示例:
class Boo {
private var myString : String = ""
var myOtherString : String = ""
}
和反编译的.java 等价物:
public final class Boo {
private String myString = "";
@NotNull
private String myOtherString = "";
@NotNull
public final String getMyOtherString() {
return this.myOtherString;
}
public final void setMyOtherString(@NotNull String var1) {
Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
this.myOtherString = var1;
}
}
为什么私有字符串属性不需要@NotNull
?
反过来想:在公共财产上提供@NotNull
有什么好处(而不是例如隐藏@Metadata
中的所有信息)? 它对 JVM 运行时没有任何意义; 主要好处是为 class 及其工具的用户提供文档,因此他们知道getMyOtherString
永远不会返回 null。 但是他们一开始就无法访问myString
,因此没有必要对其进行注释。
这并不能完全回答为什么字段myOtherString
被注释,而不仅仅是 getter 和 setter; 我猜这是因为它可以用@JvmField
,所以在某些情况下编写注释它的代码是必要的,并且不检查该字段是否可见稍微方便一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.