你可以这样做:
public Rectangle(Rectangle source) {
this(checkNotNull(source, "Source cannot be null").width, source.height);
}
private static T checkNotNull(T t, String msg) {
if (t == null) throw new IllegalArgumentException(msg);
return t;
}
我同意Jon Skeet的说法,在这种情况下,NullPointerException并不是一个坏的bevahiour.唯一的问题是,在获得NPE的长行中,可能有点难以确定哪个对象为空,这就是更具体的消息可能有用的原因.
如果你不打扰抛出NullPointerException,你也不能重新发明轮子并使用标准的java.util.Objects方法:
public Rectangle(Rectangle source) {
this(Objects.requireNonNull(source, "Source cannot be null").width, source.height);
}
如果您的错误消息构建起来很昂贵,您可以提供供应商< String>相反,只有在实际需要时才支付构建消息的成本:
public Rectangle(Rectangle source) {
this(Objects.requireNonNull(source, () -> explainError(source)).width, source.height);
}