欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

kotlin中使用Java接口,报错Parameter specified as non-null is null

程序员文章站 2024-03-20 22:19:34
...

简述

kotlin中使用Java接口,报错Parameter specified as non-null is null

问题

2021-07-06 09:33:35.053 2317-2317/com.lqbs.piot E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.lqbs.piot, PID: 2317
    java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter hittingNode

原因分析

有一个接口TreeViewControlListener.class

public interface TreeViewControlListener {
    int MIN_SCALE  = -1;
    int FREE_SCALE = 0;
    int MAX_SCALE  = 1;
    void onScaling(int state, int percent);
    void onDragMoveNodesHit(NodeModel<?> draggingNode,NodeModel<?> hittingNode,View draggingView,View hittingView);
}

对应实现

binding!!.baseTreeView.setTreeViewControlListener(object : TreeViewControlListener {
            override fun onScaling(state: Int, percent: Int) {
				...
            }

            override fun onDragMoveNodesHit(
                draggingNode: NodeModel<*>,
                hittingNode: NodeModel<*>,
                draggingView: View,
                hittingView: View
            ) {
               ...
            }
        })

当在java中调用’onDragMoveNodesHit’方法传入null参数时,会crash。如下

if(listener!=null){
    listener.onDragMoveNodesHit(draggingNode,null,draggingView,null);
}

解决方案

首先,在java接口中添加@Nullable注解,这样在自动生成Kotlin实现接口代码时,就会可空,所以改为如下

TreeViewControlListener.class

public interface TreeViewControlListener {
    int MIN_SCALE  = -1;
    int FREE_SCALE = 0;
    int MAX_SCALE  = 1;
    void onScaling(int state, int percent);
    void onDragMoveNodesHit(@Nullable NodeModel<?> draggingNode, @Nullable NodeModel<?> hittingNode, @Nullable View draggingView, @Nullable View hittingView);
}

根据实际情况,实现接口代码,添加?表示可空

override fun onDragMoveNodesHit(
    draggingNode: NodeModel<*>?,
    hittingNode: NodeModel<*>?,
    draggingView: View?,
    hittingView: View?
) {
    ....
}