如何在java中避免无空检查的NullpointerException
在下面的代码中,我想跳过空检查。请告诉我替代方案如何在java中避免无空检查的NullpointerException,java,Java,在下面的代码中,我想跳过空检查。请告诉我替代方案 public class NullCheck { public static void main(String[] args) { String str=args[0]; if (null != str) //without using this null check how to avoid null pointer exception { Syste
public class NullCheck {
public static void main(String[] args) {
String str=args[0];
if (null != str) //without using this null check how to avoid null pointer exception
{
System.out.println("Null check");
}
else
{
System.out.println("Null value");
}
}
}
谢谢我跳过了代码中的空检查。不管怎样,都不检查null值
public class NullCheck {
static String str;
public static void main(String[] args) {
}
}
更重要的是,你可以:
- 解释为什么要避免空检查
- 将
初始化为静态字符串str
(一个空字符串),它肯定不会是=”
(只需确保没有人可以为它分配null)李>null
if(“Hello”.equals(str))
“Hello”
作为一个文本,永远不会为null
,内置的equals
方法将检查str
是否为null。替代的str.equals(“Hello”)
要求您首先检查str
有些人发现它们令人困惑,因此并不总是能够相应地安排语法。另一种替代解决方案是始终将变量初始化为某个值。对于stings,这可能是一个空字符串:
string=“”代码>。对于集合,可以初始化为空集合:Collection Collection=collections.emptyList()
或Collection list=new ArrayList()
如果您想在以后添加到其中
然而,问题是,在某个时刻,您需要查看对象是否为null,因为并非每个对象都有一些默认的、安全的初始化值:
Scanner scanner = null;
try
{
scanner = new Scanner(...);
...
}
...
finally
{
if(scanner != null) scanner.close();
}
因此,我不认为您可以完全避免进行空检查,但您可以减轻它。我想有一些事情需要做吗?
最后,老师要你用试抓块
try{
//what you want to do when its not null
}
catch (NullPointerException exp){
//what happens if its null
}
它尝试在try块中执行代码,但是如果发生NullPointerException,您可以在Catch块中处理它。也许,只是也许这就是你想要的。我不知道你的检查有什么问题,这似乎是一个很好的解决方案,但你可以使用try-catch语句,或者使用默认值“”初始化str-object并检查空字符串,或者使用断言检查可为空的对象。简短回答:你不能。
详细回答:您可以使用变通方法,这实际上就是检查else是否为null
有些人已经给出了答案,我将给你一个提示(不是真正的答案,因为事实恰恰相反):
Java 8引入了泛型类:
它在内部保存对对象或null的引用。
它给您的是,每当您试图调用它所持有的对象上的方法时,为了获得实际的对象,您需要调用get()方法,这很可能会提醒您检查是否存在
只是一个小样本:
package whatever;
import java.util.Optional;
public class Main(){
public static void main(String[] args) {
Optional<String> a = Optional.empty();
Optional<String> b = Optional.ofNullable(notReallyAString);
Optional<String> c = Optional.of("John Paul II");
if(a.isPresent()) System.out.println("Empty optional, you shouldnt be able to see this");
if(b.isPresent()) System.out.println("Optional with a null, shouldnt be able to see this");
if(c.isPresent()) System.out.println(c.get());
}
}
打包任何东西;
导入java.util.Optional;
公共类Main(){
公共静态void main(字符串[]args){
可选a=可选的.empty();
可选b=可选。不可用(非真实字符串);
可选c=可选的(“约翰·保罗二世”);
如果(a.isPresent())System.out.println(“空可选,您不应该看到这个”);
如果(b.isPresent())System.out.println(“带有null的可选项,不应看到此项”);
if(c.isPresent())System.out.println(c.get());
}
}
但是请注意,它不应该是一个通用的任何值volder,您很可能只想使用Optional only作为方法的返回类型,向客户机表明它可能确实为null
请记住,尝试(通过get()方法)获取可选实例中的null元素将立即导致NoSuchElementException(但仍然是未检查的异常)良好的ol'null检查有什么问题?将str
初始化为空字符串,即静态字符串str=”“代码>然后您只需检查它是否为空;)我喜欢这个解决方案!如果有机会的话,我通常会这样编码。我想要一种空检查的替代方法。