简体   繁体   English

如何覆盖java方法,并更改参数的可为空性?

[英]How can I override a java method, and change the nullability of a parameter?

I'm overriding a method from a Java library, and the parameter for the function is annotated as @NonNull . 我正在覆盖Java库中的方法,该函数的参数注释为@NonNull However, when the method is called, the parameter frequently comes in with a null value. 但是,调用该方法时,参数通常会带有null值。 When I override the method in Kotlin, it forces me to respect the @NonNull annotation and mark the parameter as not nullable. 当我在Kotlin中覆盖该方法时,它会强制我尊重@NonNull注释并将参数标记为不可为空。 Of course, Kotlin throws an exception at run time when the parameter comes in with a null value. 当然,当参数带有空值时,Kotlin会在运行时抛出异常。 Is there some way I can override the method in Kotlin and ignore the @NonNull annotation? 有什么方法可以覆盖Kotlin中的方法并忽略@NonNull注释?

Specifically, I'm using the appcompat library for Android. 具体来说,我正在使用适用于Android的appcompat库。 The method is in AppCompatActivity.java 该方法位于AppCompatActivity.java中

@CallSuper
public void onSupportActionModeFinished(@NonNull ActionMode mode) {
}

The override in Kotlin: Kotlin中的覆盖:

override fun onSupportActionModeFinished(mode: ActionMode) {
    super.onSupportActionModeFinished(mode)
}

There seems to be no straightforward way to suppress nullability annotation handling by Kotlin compiler. 似乎没有直接的方法来抑制Kotlin编译器处理的可空性注释处理。

As a workaround, you can make an intermediate derived class with @Nullable annotation in Java: when Kotlin compiler sees both @Nullable and @NonNull on the same code element it behaves as if there were no nullability annotations. 作为一种解决方法,您可以在Java中使用@Nullable注释创建一个中间派生类:当Kotlin编译器在同一代码元素上看到@Nullable@NonNull时,它的行为就像没有可空性注释一样。 Then just subclass it in Kotlin. 然后在Kotlin中将其子类化。 Example: 例:

Consider a class with a @NonNull parameter in Java: 考虑在Java中使用@NonNull参数的类:

abstract class Base {
    public abstract void f(@NonNull String str);
    //...
}

Kotlin understands the annotation: f(str: String) , the type is non-null. Kotlin理解注释: f(str: String) ,类型为非null。

Now extend Base in Java, override the method and add @Nullable annotation to the parameter in Intermediate : 现在在Java中扩展Base ,重写方法并将@Nullable注释添加到Intermediate的参数:

abstract class Intermediate extends Base {
    @Override
    public abstract void f(@Nullable String str);
}

For Intermediate , Kotlin sees f(str: String!) , the parameter has platform type , that is, its nullability is unknown. 对于Intermediate ,Kotlin看到f(str: String!) ,该参数具有平台类型 ,即其可空性未知。

After that, you will be able to declare nullable parameter in a Kotlin subclass of Intermediate : 之后,您将能够在Intermediate的Kotlin子类中声明可为空的参数:

class Derived(): Intermediate() {
    override fun f(url: String?) { ... }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM