简体   繁体   English

为什么@TupleConstructor不生成构造函数

[英]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. 这里有两个问题。

  1. The generated constructor has wrong order of fields and hence the constructor call doesn't match. 生成的构造函数的字段顺序错误,因此构造函数调用不匹配。 This limitation arises because reflection API does not guarantee that it'll return the fields of a Java class in order they were defined. 之所以会出现此限制,是因为反射API不能保证它将按定义的顺序返回Java类的字段。 The javadoc for 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 this Class object. 返回一个包含Field对象的数组,该对象反映此Class对象表示的类或接口的所有可访问公共字段。 The elements in the array returned are not sorted and are not in any particular order . 返回的数组中的元素未排序,并且没有任何特定顺序

  1. The inner class is not static. 内部类不是静态的。 So the first argument in the constructor is expected to be an instance of enclosing class. 因此,构造函数中的第一个参数应该是封闭类的实例。

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.

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