Java null arguments when chaining Constructors

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object):

public class Rectangle {

    int width, height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public Rectangle(Rectangle source) {
        this(source.width, source.height);
    }
}

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

Jon Skeet
people
quotationmark

Yes, you can use a helper method which will throw the exception if necessary, and return the original value otherwise... you can call that within your constructor invocation, as you're allow method calls as part of argument evaluation.

// In a helper class
public static <T> T checkNotNull(T value) {
    if (value == null) {
        throw new IllegalArgumentException();
    }
    return value;
}

Then use it as:

public Rectangle(Rectangle source) {
    this(Helper.checkNotNull(source).width, source.height);
}

However... I believe that NullPointerException is the recommended exception to throw here anyway (in Effective Java 2nd edition, for example), which your existing code will throw already. So you quite possibly don't want to make any change to your existing code.

If you want a helper method for checks like this but are happy for it to throw NullPointerException, I'd recommend using Guava and its Preconditions class, which has this and a lot of other helpful 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.

people

See more on this question at Stackoverflow