构造函数可以中止实例化吗?

Tom*_*ola 1 java constructor

我想在构造函数中进行测试,以确定当前是否使用给定参数实例化对象是一个好主意.但是我如何中止并从构造函数向新语句返回警告?在每个"新"声明之前,调用者是否必须进行此类测试?我认为构造函数对它来说是个好地方.

Gav*_*ell 9

您可以使用工厂对象.然后,这可以运行您的检查并返回instansiated对象,或null.这可能比例外更有效.

MyObject myObject = MyObjectFactory.createMyObject();
Run Code Online (Sandbox Code Playgroud)

  • +1,请执行此操作而不是投入构造函数. (2认同)

Spo*_*ike 5

是的,您在构造函数中抛出异常.

在java中你通常抛出一个IllegalArgumentException如果其中一个参数是错误的,这是一个常见的做法作为一个守护声明:

public class Roman {

    public Roman(int arabic) {

        // "Guard statement" in the beginning of the constructor that
        // checks if the input is legal
        if (arabic < 0) {
            throw new IllegalArgumentException("There are no negative roman numerals");
        }

        // Continue your constructor code here

    }

}
Run Code Online (Sandbox Code Playgroud)

如果你不想要例外,你可以做GavinCatelli的答案,并创建一个工厂方法,如果对象不是"正确",则返回null.

public class RomanFactory {

    public static Roman getSafeRoman(int a) {
        Roman r;
        try {
            r = new Roman(a);
        } catch(IllegalArgumentException e) {
            r = null;
        }
        return r;
    }

}
Run Code Online (Sandbox Code Playgroud)

您必须检查null,否则程序可能会因NullPointerException而崩溃.