How to avoid NullPointerException in if condition

I have to take few actions depending upon the if condition. Say I have an enum "VoucherType"

Now I have a code, that is executed depending upon the condition:-

private boolean verifyGiveAwayAccounting(GiveAwayMoneyVerificationEvent event) {

    if(event.getVoucherType().equals(VoucherType.GIVE_AWAY_MONEY_ON_SIGNUP)){
        someAction();
    }
    return verifySystemAccountTransaction(event);
}

I have to perform someAction() if the event is of type "GIVE_AWAY_MONEY_ON_SIGNUP" . But I do not have to do anything extra is event type is anything other than "GIVE_AWAY_MONEY_ON_SIGNUP". So when I call this code I set the voucherType to "GIVE_AWAY_MONEY_ON_SIGNUP" and someAction() is executed.

But for any other type of events, I get null pointer exceptions in the if condition as I never set the voucher type as I do not want to do anything special. So in order to avoid the nullPointerException I set the Voucher code to something dummy(other voucherType values) which I never use in any conditions. I there a sophisticated way I can eliminate the nullPointerException without initializing the VoucherType in event?


在对这个对象的属性进行测试之前,你应该总是测试你的对象是否为空。

if(enum != null && enum.Football) {
  //some action
}

If event is never null , in this case perhaps you can invert your test :

private boolean verifyGiveAwayAccounting(GiveAwayMoneyVerificationEvent event) {
    if(VoucherType.GIVE_AWAY_MONEY_ON_SIGNUP.equals(event.getVoucherType())){
            someAction();
    }
    return verifySystemAccountTransaction(event);
}

otherwise you should test if event is not null before :

private boolean verifyGiveAwayAccounting(GiveAwayMoneyVerificationEvent event) {
    if(event != null && VoucherType.GIVE_AWAY_MONEY_ON_SIGNUP.equals(event.getVoucherType())){
            someAction();
    }
    return verifySystemAccountTransaction(event);
}

As defined by WikiBooks:

A NullPointerException is thrown when an application attempts to use an object reference, having the null value. These include: Calling an instance method on the object referred by a null reference.

If you do not instantiate the enum value, it will have a value of null . Thus, the program is attempting to reference an object that contains null , which throws a NullPointerException .

Therefore, no, there is no way to avoid your NullPointerException . You need to instantiate variables before attempting to reference them.

链接地址: http://www.djcxy.com/p/91846.html

上一篇: 关于Java中死锁情况的问题

下一篇: 如何在if条件中避免NullPointerException