JAVA 判断空

来源:互联网 发布:淘宝县级服务站加盟 编辑:程序博客网 时间:2024/05/16 09:13

JAVA 判断空

判断对象空是java必学的一个过程,任何一个初学者或者更高级开发人员也会遇到空指针异常。那么如何才能避免空指针呢?为了避免空指针异常,java代码里面出现了很多 != null 判断语句,StringUtils.isNotBlank(str) 等语句。那么如何减少判断空的语句呢?在开发接口中,如果形参是必须的,则必须要对形参进行非空判断。如果接口返回的是Collection 集合,避免返回null对象,而是Collections.EmptyList,调用方接收到返回结果则可以不用判断空了。如果接口返回的不是Collection 集合,需要使用空对象(非null),new 一个空的对象:实例:
public interface Action {  void doSomething();}public interface Parser {  Action findAction(String userInput);}
    其中,Parse有一个接口findAction,这个接口会依据用户的输入,找到并执行对应的动作。假如用户输入不对,可能就找不到对应的动作(Action),因此findAction就会返回null,接下来action调用doSomething方法时,就会出现空指针。 解决这个问题的一个方式,就是使用Null Object pattern(空对象模式)我们来改造一下类定义如下,这样定义findAction方法后,确保无论用户输入什么,都不会返回null对象 
public class MyParser implements Parser {     private static Action DO_NOTHING = new Action() { public void doSomething() { /* do nothing */ } };public Action findAction(String userInput) { // ... if ( /* we can't find any actions */ ) { return DO_NOTHING; } }}
    对比下面两份调用实例 1. 冗余: 每获取一个对象,就判一次空Parser parser = ParserFactory.getParser();if (parser ==null) {  // now what?// this would be an example of where null isn't (or shouldn't be) a valid response}Action action = parser.findAction(someInput);if (action ==null) {  // do nothing } else {      action.doSomething();  }
    精简:ParserFactory.getParser().findAction(someInput).doSomething();    因为无论什么情况,都不会返回空对象,因此通过findAction拿到action后,可以放心地调用action的方法。
0 0