Varargs Null Checking

May 8th, 2009

VarArgs Null checking? This should be easy, right? All we need to do is put a “VarArgs”.length == 0 check before the important method’s body and we are set (See Checker class), correct?


class Checker {
	public void check(Arg... args){
		if(args.length == 0) return;
		final List<Arg> someArgs = Arrays.asList(args);
		for(Arg each: someArgs){
			System.out.println("checked:" + each.toString());
		}
	}
}

class Arg{
  private final String name;
  Arg(String name){this.name = name;}
  @Override public String toString(){return name;}
}

The above check should work nicely under the following circumstances


new Checker().check(new Arg("one"), new Arg("two"));
new Checker()

Unfortunately, it won’t work under the following one, which will actually throw the exception that you were trying to avoid: NullPointerException.


new Checker().check(null, null); // Ooh! a NullPointerException....

how to fix this? Easy…


class Checker {
	public void check(Arg... args){
		if(args.length == 0 || Arrays.asList(args).contains(null)) return;
		final List<Arg> someArgs = Arrays.asList(args);
		for(Arg each: someArgs){
			System.out.println(each.toString());
		}
	}
}

This should definitely work nicely. This is all for today. Until next time.

programming | Comments | Trackback

Leave a Reply

  1.  
  2.  
  3.  
  4. XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
  5. Spam Protection by WP-SpamFree

You can keep track of new comments to this post with the comments feed.

 

May 2009
M T W T F S S
« Jan   Jul »
 123
45678910
11121314151617
18192021222324
25262728293031

Categories

Archives

Tags