Record a null pointer exception caused by Java Convert Kotlin

I don’t know if you use Code -> Convert Java File 2 Kotlin Filethe function of AS directly when you use Kotlin for coding. This function is quite practical in daily use. It can help us convert old Java or copied Java code into Kotlin code with one click. Recently, when using this function, I encountered a crash of a null pointer. I will record it here and give you a warning by the way.

origin

A three-party SDK is introduced into the project. This SDK uses Java coding. We need to implement a callback method of it to handle exceptions. The specific methods of the SDK will not be posted. Let’s simulate their callbacks

public class Test {
    
    

    // 定义回调接口,其中error用来处理异常情况,参数为Exception对象
    public interface TestCallback {
    
    
        void test();

        void error(Exception e);
    }

    // 传入回调并直接模拟调用它的方法
    public void setTest(TestCallback testCallback) {
    
    
        testCallback.test();
        testCallback.error(new Exception("test"));
    }
}

Simulate their callback interface, and then setTest(callback)call the interface method directly in it. Let’s take a look at this errorinterface method first. Its parameters exceptionare not defined with nullable ( @Nullable) or non-nullable ( @NonNull) annotations, and the default is the nullable type.

Then we directly simulate the call to see the specific effect, first use Java code to call

public class Java2Kt {
    
    

    private final Test testCallback = new Test();

    public void test() {
    
    
        testCallback.setTest(new Test.TestCallback() {
    
    
            @Override
            public void test() {
    
    
                Log.d("taonce", "Java2Kt test");
            }

            @Override
            public void error(Exception e) {
    
    
                if (e != null) {
    
    
                    Log.d("taonce", "Java2Kt error " + e.getMessage());
                }
            }
        });
    }
}

# 
Java2Kt test
Java2Kt error java.lang.Exception: custom exception

In this way, there is nothing wrong with it, and the log can be called and output correctly. Then we change setTest(callback)the method and add an extra line

public void setTest(TestCallback testCallback) {
    
    
    testCallback.test();
    testCallback.error(new Exception("test"));
    // 新增
    testCallback.error(null);
}

Even if we error()pass in the call, nullthere will be no problem, because we added non-empty judgment when the callback is implemented, but we Convert Java File 2 Kotlin Filewill look at the code after converting to Kotlin

class Java2Kt {
    
    
    private val testCallback = Test()
    fun test() {
    
    
        testCallback.setTest(object : TestCallback {
    
    
            override fun test() {
    
    
                Log.d("taonce", "Java2Kt test")
            }

            override fun error(e: Exception) {
    
    
                if (e != null) {
    
    
                    Log.d("taonce", "Java2Kt error " + e.message)
                }
            }
        })
    }
}

In this way, at first glance, there will be no problem, because after converting to KT, there is also a non-empty judgment, but at this time AS will report a warning at the place of the non-empty judgment, reminding us, and habitually will use this non- Condition 'e != null' is always 'true'null To remove, after removing a run directly to a null pointer exception

analyze

Convert Java File 2 Kotlin FileDuring the conversion process of the function of AS, if the parameter does not use nullable or non-null annotations, the default type is non-null after conversion, which will cause us to pay less attention to the nullable type of this parameter when using it, and sometimes lose the nullable type . Check, so that there will be a possibility of a null pointer during the running of the program, and then look at the code that directly uses KT to implement the callback

test.setTest(object : Test.TestCallback {
    
    
    override fun test() {
    
    
        Log.d("taonce", "MainActivity test")
    }
    // 默认为可空类型
    override fun error(e: Exception?) {
    
    
        Log.d("taonce", "MainActivity test ${e?.stackTraceToString()}")
    }
})

If you directly use KT to encode, the implementation will add nullable (?) by default, and clearly inform developers that this parameter may be null, and you need to add a nullable judgment when using it TestCallback. error(exception?)Therefore, there is a high probability that using KT directly will not cause a null pointer.

summary

  1. The function of AS Convert Java File 2 Kotlin Filecertainly provides convenient operation for developers, but it also requires careful judgment by developers after use.
  2. For some callbacks written in Java, add nullable or non-nullable annotations as much as possible to provide some warning information to the caller
  3. In daily coding, coding details must be handled properly. Null pointers are unavoidable, but such exceptions need to be avoided as much as possible. KT has provided developers with relatively safe operations in this regard.

at last

If you want to become an architect or want to break through the 20-30K salary range, then don't be limited to coding and business, but you must be able to select models, expand, and improve programming thinking. In addition, a good career plan is also very important, and the habit of learning is very important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.

If you have no direction, here I would like to share with you a set of "Advanced Notes on the Eight Major Modules of Android" written by the senior architect of Ali, to help you organize the messy, scattered and fragmented knowledge systematically, so that you can systematically and efficiently Master the various knowledge points of Android development.
insert image description here
Compared with the fragmented content we usually read, the knowledge points of this note are more systematic, easier to understand and remember, and are arranged strictly according to the knowledge system.

Full set of video materials:

1. Interview collection

insert image description here
2. Source code analysis collection
insert image description here

3. The collection of open source frameworks
insert image description here
welcomes everyone to support with one click and three links. If you need the information in the article, directly scan the CSDN official certification WeChat card at the end of the article to get it for free↓↓↓

PS: There is also a ChatGPT robot in the group, which can answer your work or technical questions

Guess you like

Origin blog.csdn.net/datian1234/article/details/130932082