kalsowerus kalsowerus - 10 months ago 54
Java Question

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
in the copy-constructor and throw an
if it is? Because the other constructor call has to be the first statement in my constructor.


You can do this:

public Rectangle(Rectangle source) {
     this(checkNotNull(source, "Source cannot be null").width, source.height);

private static <T> T checkNotNull(T t, String msg) {
    if (t == null) throw new IllegalArgumentException(msg);
    return t;

I also agree with Jon Skeet that a NullPointerException is not a bad bevahiour in this case. The only thing is that in long lines when you get an NPE it can be a bit hard to identify which object is null, which is why a more specific message can be useful.

You can also not reinvent the wheel and use standard java.util.Objects methods if you don't bother throwing a NullPointerException instead:

public Rectangle(Rectangle source) {
     this(Objects.requireNonNull(source, "Source cannot be null").width, source.height);

if your error message is expensive to build, you can provide a Supplier<String> instead, to pay the cost of the construction of the message only when it's actually needed:

 public Rectangle(Rectangle source) {
     this(Objects.requireNonNull(source, () -> explainError(source)).width, source.height);