gpt4 book ai didi

java - 是否有任何工具可以检测类成员变量中可能出现的 NullPointerException

转载 作者:太空狗 更新时间:2023-10-29 15:28:23 27 4
gpt4 key购买 nike

当我们用下面的类创建一个对象后肯定会抛出一个 NullPointerException,因为成员变量 mTest 为 null,

public class SettingsActivity extends PreferenceActivity {
private String mTest;

// the setter is not being called after the object is created
public void setTest(String test) {
mTest = test;
}

// ok, the activity is starting and will crash
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);

mTest.replace("a", "b");
}

}

在一些 Activity 中,

Intent intent = new Intent(this, SettingsActivity.class);
// we forgot to set the member variable...
startActivity(intent);

我们正在使用 SonarQube 和 Android Studio 来检测空指针引用,但它们都无法检测到上述问题。有什么建议吗?我知道程序员不应该编写这些错误,但我更感兴趣的是检测它们而不是修复它们。

谢谢!

最佳答案

尝试使用 try/catch block ,让 catch block 看起来像这样:

catch (Exception e){
e.printStackTrace(System.out);
}

这里的 System.out 可以替换为任何输出格式(记录器、打印器等)

关于java - 是否有任何工具可以检测类成员变量中可能出现的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18310178/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com