简体   繁体   English

在groovy和lombok @Value中命名参数构造函数

[英]Named parameter constructor in groovy and lombok @Value

I have following object annotated with @Value from Lombok: 我有来自Lombok的@Value注释的跟随对象:

@Value
public class Foo {
    private final boolean bar;
    private final boolean baz;
    private final boolean boo;
}

I try to instantiate Foo from groovy test: 我尝试从groovy测试中实例化Foo

new Foo(bar: true, baz: false, boo: true)

but I get warning: 但我收到警告:

Constructor 'Foo' cannot be applied to '()'

and during runtime following error: 并在运行时跟随错误:

Cannot set readonly property: bar for a class: Foo

is there a way to use named constructor in groovy that will call constructor with all arguments instead of calling empty constructor and then trying to set fields? 有没有办法在groovy中使用命名构造函数,它将调用所有参数的构造函数,而不是调用空构造函数,然后尝试设置字段?

Constructor 'Foo' cannot be applied to '()'

This appears because all fields in your class are final, so you have to initiate these fields during object initialization. 出现这种情况是因为类中的所有字段都是final,因此您必须在对象初始化期间启动这些字段。

So the only way to create an object of this class is to use all-args constructor: 因此,创建此类对象的唯一方法是使用all-args构造函数:

new Foo(true, false, true)

Due to the way, Groovy handles what looks like named arguments (Groovy does not support named arguments - it passes a Map), this will also fail with similar Groovy code. 由于这种方式,Groovy处理看起来像命名的参数(Groovy 支持命名参数 - 它传递Map),这也将失败与类似的Groovy代码。 The way Groovy handles the map passing here, is by unrolling the map into setter calls (and there are none because the attributes are final). Groovy处理地图传递的方式是将地图展开到setter调用中(并且没有因为属性是final的)。

@groovy.transform.TupleConstructor
class Foo {
    final boolean bar
    final boolean baz
    final boolean boo
}

new Foo(bar: true, baz: false, boo: true)

Fails with 失败了

Caught: groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: bar for class: Foo
groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: bar for class: Foo
        at x.run(x.groovy:8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM