如何防止使用默认构造函数?

TWi*_*Rob 0 groovy constructor instantiation default-constructor

我在Java编译器中长大,只要类中没有显式构造函数,就会自动生成一个默认构造函数; 当我有任何显式构造函数时不生成.

据我所知,构造函数定义了所需的依赖项,属性定义了可选的依赖项(很可能是默认值...由构造函数设置).如果你坚持上述规则(我在职业生涯中根据经验选择),那么在面向对象的代码中能够在<init>() 没有定义时调用是完全错误的.

这是一个我尝试过的简单测试,并注意到即使使用显式构造函数,也可以很容易地实例化没有args的对象.如何在编译时或运行时在标有????的行上使该程序失败?

class TestGroovy {
    private final String name
    TestGroovy(String name) {
        this.name = name
    }

    static void main(String[] args) {
        testStatic()
        println()
        testDynamic()
        println()
        testReflection()
    }

    @groovy.transform.CompileStatic
    static void testStatic() {
        println new TestGroovy("static");
        println "compile error"
        // Groovyc: [Static type checking] - Cannot find matching method TestGroovy#<init>().
        // Please check if the declared type is right and if the method exists.
        //println new TestGroovy(); // correct
    }

    static void testDynamic() {
        println new TestGroovy("dynamic");
        println new TestGroovy(); // ???
    }

    static void testReflection() {
        println TestGroovy.class.newInstance([ "reflection" ] as Object[]);
        println TestGroovy.class.newInstance(); // ???
    }

    @Override String toString() { return "Name: ${name}"; }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Name: static
compile error

Name: dynamic
Name: null

Name: reflection
Name: null
Run Code Online (Sandbox Code Playgroud)

预期:RuntimeException而不是Name: null.

我试图在Groovy文档中找到相应的部分,但我没有找到任何真正相关的部分.我找的关键词是default constructor,no-arg constructor,no-args constructor,no-arguments constructor.

虽然这是一个远程相关的:

命名参数构造函数
如果没有声明构造函数,则可以创建对象[...]

据我所知,位置构造函数是声明的和Java类似的,如果没有明确的位置构造函数,你可以使用命名构造函数.我有一个想法,上面(in testDynamic())的默认构造函数调用实际上正在工作,因为它使用空映射调用命名构造函数,但我在命名构造函数部分以"如果没有声明构造函数声明"开头时快速排除了这一点,并且我显然有一个.

bla*_*rag 6

在Groovy中,您可以调用不带参数的单个参数方法.Null将在那时使用.(除非参数具有基本类型,否则调用失败).所以对于Groovy来说,为构造函数执行此操作也是完全合法的.计划在将来删除该功能.因此我们决定静态groovy编译器不会支持它.这就是静态编译器在这里编译失败的原因.因此,不会生成no-args构造函数,使用null值调用现有的String兼容值构造函数.如果您绝对想要阻止这种情况,可以尝试元编程来替换构造函数并添加空检查.Groovy不会在这里为您抛出异常

  • 这有记录在任何地方吗?(注意:我不考虑[此标注](http://docs.groovy-lang.org/latest/html/documentation/#_creating_instances_of_non_static_inner_classes)文档,因为它是不相关的地方)。我想它*将*记录在[方法选择算法](http://docs.groovy-lang.org/latest/html/documentation/#_method_selection_algorithm)。 (2认同)