我使用聲納和我有這種違規從它的對我的代碼和平:findbug中可能的空指針解除引用是什麼意思?
Correctness - Possible null pointer dereference
有沒有人知道在這個FindBugs的規則?我搜索了很多,但是我找不到一個很好的示例代碼(用Java編寫)描述了這條規則,不幸的是findbugs網站沒有任何示例代碼或者關於這條規則的很好的描述。
爲什麼會出現此違規行爲?
我使用聲納和我有這種違規從它的對我的代碼和平:findbug中可能的空指針解除引用是什麼意思?
Correctness - Possible null pointer dereference
有沒有人知道在這個FindBugs的規則?我搜索了很多,但是我找不到一個很好的示例代碼(用Java編寫)描述了這條規則,不幸的是findbugs網站沒有任何示例代碼或者關於這條規則的很好的描述。
爲什麼會出現此違規行爲?
它說here
NP: Possible null pointer dereference (NP_NULL_ON_SOME_PATH)
有說法的一個分支,如果執行,保證空值將被廢棄時,被執行的代碼時會產生一個NullPointerException。當然,問題可能是分支或語句不可行,並且空指針異常不能執行;決定超出FindBugs的能力。
,如果您已經發布了一些代碼,它會更容易回答。
編輯我沒有看到很多文檔,但這裏有一個example!希望這可以幫助!
我的代碼非常複雜,我也改變了我的代碼,它修復了,但我不明白這個findbugs規則。 –
比好,因爲它說'有說法的一個分支,如果執行,保證空值將被廢棄時,當代碼是executed.'意味着你可能是一個分配'null'這將產生一個NullPointerException變量並再次使用它可能會導致異常。 – SiB
請給我一個示例代碼。我之前閱讀過這個描述! –
示例代碼是這樣的。
String s = null ;
if (today is monday){
s = "Monday" ;
else if (today is tuesday){
s = "Tuesday" ;
}
System.out.println(s.length()); //Will throw a null pointer if today is not monday or tuesday.
好
這是兩個簡單的例子: 一人給一個:可能的空指針引用
1. Error
ArrayList a = null;
a.add(j, PointSet.get(j));
// now i'm trying to add to the ArrayList
// because i'm giving it null it gives me the "Possible null pointer dereference"
2. No Error
ArrayList a = new ArrayList<>();
a.add(j, PointSet.get(j));
// adding elements to the ArrayList
// no problem
簡單嗎?
用簡單的語言,如果變量值被指定爲null,並且您嘗試使用任何內置方法(如add/get)來訪問它。然後,SONAR會附帶空指針取消引用問題。因爲它有變化,所以會變爲null,並拋出空指針異常。儘可能避免它。
Ex File file = null; file.getName(); 將拋出「可能的空指針解除引用」
它可能不會像例子中提到的那樣直接發生,它可能是無意的。
我得到這個問題與下面的代碼段: -
BufferedReader br = null;
String queryTemplate = null;
try {
br = new BufferedReader(new FileReader(queryFile));
queryTemplate = br.readLine();
} catch (FileNotFoundException e) {
// throw exception
} catch (IOException e) {
// throw exception
} finally {
br.close();
}
這裏,br
的BufferedReader可以在br.close()
null
。但是如果new BufferedReader()
失敗,它只能是null
,在這種情況下,我們拋出相關的例外。
這是一個錯誤的警告。Findbugs
docs提及相同: -
This may lead to a NullPointerException when the code is executed.
Note that because FindBugs currently does not prune infeasible
exception paths, this may be a false warning.
發佈一些代碼,其中的建議顯示! – SiB
我想查看關於此findbugs規則的示例代碼。我想普遍知道它。 –