Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check null for getter methods in java

Tags:

java

I have a POJO class.

class Activity{
   private String name;

   public String getName()
      return name;
   }

   public void setName(String name){
      this.name=name;
   }
}

im having belw condtions.its not enr=ering properly in those condtions accordingly

 if(stlmtTransRequestVO.getStlmtTransId()!=null && stlmtTransRequestVO.getPaymentTransId()!=null){
stlmtTransDtlsList = (List<StlmtTransResponseVO>) queryForList(
        "GET_STLMTPAY_TRANSACTIONS", stlmtTransRequestVO);


 }else if(stlmtTransRequestVO.getAgentId()!=null && stlmtTransRequestVO.getAgencyId()==null){
stlmtTransDtlsList = (List<StlmtTransResponseVO>) queryForList(
        "GET_AGENT_TRANSACTIONS", stlmtTransRequestVO);

 }else if(stlmtTransRequestVO.getAgencyId()!=null && stlmtTransRequestVO.getAgentId()==null){
stlmtTransDtlsList = (List<StlmtTransResponseVO>) queryForList(
        "GET_AGENCY_TRANSACTIONS", stlmtTransRequestVO);

 }else if(stlmtTransRequestVO.getAgencyId()!=null && stlmtTransRequestVO.getAgentId()!=null){

}

How to check this getter method for having data or not?

I have tried below scenarios but not working

   1) obj.getName()!=null
   2) obj.getName().isEmpty()
like image 383
Manu Avatar asked Jan 10 '13 11:01

Manu


People also ask

How do you check if it is null in Java?

In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.

How do you do a null check?

Use "==" to check a variable's value. If you set a variable to null with "=" then checking that the variable is equal to null would return true.


3 Answers

obj.getName() != null is right. But it depends on your definition of "having data". It might be: object.getName() != null && !obj.getName().isEmpty().

There are utilities to facilitate that, like apache commons-lang StringUtils.isNotEmpty(..)

like image 143
Bozho Avatar answered Nov 12 '22 20:11

Bozho


if( obj.getName() != null && !"".equals(obj.getName()) ){
   //getName is valid
} 

Above is checking that name is not null and also it's not empty. Also "".equals(obj.getName()) is considered better approach than obj.getName().equals("").

like image 43
rai.skumar Avatar answered Nov 12 '22 21:11

rai.skumar


Initialize like this:

private String name = "";

Then you can check it with:

obj.getName().isEmpty();
like image 22
Adrián Avatar answered Nov 12 '22 20:11

Adrián