Yes, you can use a helper method that will throw an exception if necessary and return the original value otherwise ... you can call this in a constructor call, because you allow method calls as part of evaluating the arguments.
// In a helper class public static <T> T checkNotNull(T value) { if (value == null) { throw new IllegalArgumentException(); } return value; }
Then use it like:
public Rectangle(Rectangle source) { this(Helper.checkNotNull(source).width, source.height); }
However ... I believe that NullPointerException is the recommended exception to throw it at all (e.g. in Effective Java 2nd edition, for example), which will already use your existing code. Thus, you may not want to make any changes to your existing code.
If you need a helper method for such checks, but he is glad that he threw a NullPointerException , I would recommend using Guava and its Preconditions class, which has this and many other useful checking methods.
Also note that Java 1.7 introduced java.util.Objects , which has requireNonNull , so you don't even need a third-party library.
Jon skeet
source share