假设我有一个带有多个构造函数的类,其中一个是复制构造函数(用于复制对象):
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);
}
}
有没有什么办法可以让检查,如果source
是null
在拷贝构造函数和抛出IllegalArgumentException
,如果它是什么?因为另一个构造函数调用必须是构造函数中的第一条语句。
你可以这样做:
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;
}
我也同意乔恩·斯凯特(Jon Skeet)的NullPointerException
观点,在这种情况下a 并不是一个坏习惯。唯一的问题是,当获得NPE时,排长队很难识别哪个对象null
,这就是为什么更具体的消息有用的原因。
如果您不费吹灰之力,也无法重新发明轮子并使用标准java.util.Objects
方法NullPointerException
:
public Rectangle(Rectangle source) {
this(Objects.requireNonNull(source, "Source cannot be null").width, source.height);
}
如果错误消息的构建成本很高,则可以提供一个Supplier<String>
替代消息,仅在实际需要时才支付构建消息的成本:
public Rectangle(Rectangle source) {
this(Objects.requireNonNull(source, () -> explainError(source)).width, source.height);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句