Posted on May 8, 2009

Varargs Null Checking

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.