[英]Why doesn't @TupleConstructor generate constructor
class Test {
@TupleConstructor(includeFields=true)
static class TestObject {
private int a = 1;
protected int b = 2;
public int c = 3;
int d = 4;
String s = "s";
}
static main(args) {
print new TestObject(1, 2, 3, 4, '3')
}
}
Gives me: 给我:
Caught: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: in.ksharma.Test$TestObject(java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.String)
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: in.ksharma.Test$TestObject(java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.String)
at in.ksharma.Test.main(Test.groovy:17)
Why didn't it generate the constructor? 为什么不生成构造函数?
If you do: 如果您这样做:
TestObject.constructors.each {println it}
You will see that @TupleConstructor
has generated following constructors: 您将看到@TupleConstructor
生成了以下构造函数:
public in.ksharma.Test$TestObject(in.ksharma.Test,int,java.lang.String,int,int,int)
public in.ksharma.Test$TestObject(in.ksharma.Test,int,java.lang.String,int,int)
public in.ksharma.Test$TestObject(in.ksharma.Test,int,java.lang.String,int)
public in.ksharma.Test$TestObject(in.ksharma.Test,int,java.lang.String)
public in.ksharma.Test$TestObject(in.ksharma.Test,int)
public in.ksharma.Test$TestObject(in.ksharma.Test)
There are two issues here. 这里有两个问题。
Class.getFields()
says this: Class.getFields()
的Javadoc这样说: Returns an array containing
Field
objects reflecting all the accessible public fields of the class or interface represented by thisClass
object. 返回一个包含Field
对象的数组,该对象反映此Class
对象表示的类或接口的所有可访问公共字段。 The elements in the array returned are not sorted and are not in any particular order . 返回的数组中的元素未排序,并且没有任何特定顺序 。
To fix it make the nested class static and use named parameter notation: 要解决此问题,请将嵌套类设为静态并使用命名参数表示法:
print new TestObject(a:3, b:3, c:4, d:5, s:'3')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.