我处理了一些代码,并遇到了一个空指针异常,这是一个未初始化变量的结果。因此,我只是想知道:在尝试处理对象之前,是否有一种方法可以验证对象的实际存在,从而避免这样的错误?
发布于 2018-07-02 22:34:00
如何判断变量是否已初始化?
if (object != null) {
// Object has been initialized
} else {
// Object is null, which means not yet initialized
}
如何处理一个尚未初始化的变量,换句话说,空对象?
try {
// Do something with the object
} catch (NullPointerException e) {
e.printStackTrace();
}
发布于 2018-07-02 22:58:19
只需简单地使用if -子句来检查,如果对象不是空的。如果是这样的话,它已经初始化了。否则,还没有使用NullPointerException删除这些冗余的try子句,因为您可以轻松地检查和避免空对象类型。
示例:
//your code below, the String object is just an example
String text = null;
if(text!=null) {
//object has been initialized
} else {
//object has not been initialized
}
发布于 2018-07-02 23:21:19
最普遍的方法是:
Object obj
//whatever code...
if(obj != null){
//obj exists
}
else{
/*Handle the case where object doesn't exist, typically - trying to initialize it, but that's not the only case, actually lots of options available.*/}
但是,如果您知道关于对象类型的任何信息,或者它可能没有被初始化的原因,那么最好使用更具体的东西。例如,字符串的org.apache.commons.lang.StringUtils.isBlank(String str)
还有:https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#isNull-java.lang.Object-,https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#requireNonNull-T-和其他一些在上面2附近的方法
https://stackoverflow.com/questions/51144412
复制相似问题