1

I have a class

Class Test{

private String something ;
private String somethingElse;
private String somethingMore;

}

I am creating an instance of this.

myInst = new Test();

and adding values to first and second variables.

Now I need to check if any of the variable is null.

I know I can do this like if(myInst.something == null)

but for each item I add to the class it's difficult to do.

Is there anyway that i can check the instance by looping through all elements and seeing anything is null.

just like -

 for(i=0; i< myInstanceVariables ; i++)
{

if(myInstanceVariable == null ){

//do something 
donotDisplay(myInstanceVariable)

}

TIA

2
  • you can use reflection for these purposes Commented Jun 6, 2014 at 10:24
  • By reflection::Get the variable names and loop through them and check the values in that loop?Whats the problem here? Commented Jun 6, 2014 at 10:31

3 Answers 3

2

You can use Reflection using Fields from your instance. In your class, add this code. It will take all the fields and get their value.

Field[] fields = getClass().getDeclaredFields(); // get all the fields from your class.
for (Field f : fields) {                         // iterate over each field...
    try {
        if (f.get(this) == null) {               // evaluate field value.
            // Field is null
        } 
    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    }
}

Here is a sample code: https://ideone.com/58jSia

Sign up to request clarification or add additional context in comments.

1 Comment

You have to use getDeclaredFields() as opposed to getFields() to get instance variables
0

You have to use reflection over Field of the Class.

myInst = new Test();
for (Field field : myInst.getClass().getDeclaredFields())
  if (field.get(myInst) == null)
     // do something 

Comments

0

You can use reflection, however, in your case you only have String values, and thus it would also make sense to use a HashMap (for instance):

HashMap hm = new HashMap();
hm.put("something", "itsValue");
hm.put("somethingElse", null);

Now you can put as many values as you would like, and iterate through them like this:

Set set = hm.entrySet();
Iterator i = set.iterator();

while(i.hasNext()){
  Map.Entry me = (Map.Entry)i.next();
  System.out.println(me.getKey() + " : " + me.getValue() );
}

1 Comment

It makes sense, but String keys don't throw error at compilation, so personally I prefer not to use such a solution when it's possible to do it without String keys. (That's also why I prefer Annotation than XML configuration in frameworks).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.