在复制ctor,Java中调用super()之前进行空检查

1 java null nullpointerexception copy-constructor

我有一个实现接口形状的基类Polygon,以及另一个扩展Polygon的类Triangle,现在在Triangle复制构造函数中我需要检查给定的另一个三角形是不是空指针但是我不能这样做,因为我必须使用super()以初始化我的点数组.

这是我的代码:Polygon - 抽象类:

public abstract class Polygon implements Shape {
private Point[] points;

/**
 * Build a Polygon that hold a set of Points.
 * 
 * @param points
 *            (Point[])
 */
public Polygon(Point[] points) {
    this.points = points;
}
Run Code Online (Sandbox Code Playgroud)

三角形子类:

public class Triangle extends Polygon {

/**
 * Constructor.
 * Build a Triangle from 3 Point's.
 * @param p1
 * @param p2
 * @param p3
 */
public Triangle(Point p1, Point p2, Point p3) {
    super(new Point[] { p1, p2, p3 });
}

/**
 * Copy constructor.
 * @param other
 */
public Triangle(Triangle other) {
    /*
     * *********************************************
     * 
     * Here is where i want to make the null check .
     * 
     * *********************************************
     */
    super(other.getPoints().clone());
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Luk*_*der 5

使用静态辅助方法:

public Triangle(Triangle other) {
    super(clonePoints(other));
}

private static Point[] clonePoints(Triangle other) {
     if (other == null) {
         // ...
     }

     return other.getPoints().clone();
}
Run Code Online (Sandbox Code Playgroud)

另外,我经常做的是创建一个更通用的帮助方法:

public Triangle(Triangle other) {
    super(neverNull(other).getPoints().clone());
}

private static <S extends Shape> S neverNull(S notNull) {
     if (notNull == null) {
         // throw a meaningful exception 
         // or return a default value for S if possible / reasonable
     }

     return notNull;
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,Guava 有一个内置的 `Preconditions.checkNotNull()` 方法可以做到这一点,而 JDK 从版本 7 开始就有 `Objects.requireNonNull()`。 (2认同)