如何将Groovy列表转换为对象?

4
我正在遵循关于使用列表和映射作为构造函数的这篇博客文章。
为什么跟随此列表会失败而无法强制转换为对象?
class Test {
    static class TestObject {
        private int a = 1;
        protected int b = 2;
        public int c = 3;
        int d = 4;
        String s = "s";
    }

    static main(args) {
        def obj = [1, 2, 3, 4, 's'] as TestObject
    }
}

我收到了这个异常:
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '[1, 2, 3, 4, s]' with class 'java.util.ArrayList' to class 'in.ksharma.Test$TestObject' due to: 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)
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '[1, 2, 3, 4, s]' with class 'java.util.ArrayList' to class 'in.ksharma.Test$TestObject' due to: 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:22)
2个回答

5
您可以使用地图:
class Test {
    static class TestObject {
        private int a = 1;
        protected int b = 2;
        public int c = 3;
        int d = 4;
        String s = "s";
    }

    static main(args) {
        def o = ['a':1,b:'2',c:'3','d':5,s:'s'] as TestObject
        println o.d
    }
}

稍后会考虑列表。

编辑

嗯,我不确定是否可以使用列表。除非您添加适当的构造函数。完整示例:

class Test {
    static class TestObject {
        TestObject() {
        }

        TestObject(a,b,c,d,s) {
            this.a = a
            this.b = b
            this.c = c
            this.d = d
            this.s = s
        }


        private int a = 1;
        protected int b = 2;
        public int c = 3;
        int d = 4;
        String s = "s";
    }

    static main(args) {
        def obj = ['a':1,b:'2',c:'3','d':5,s:'s'] as TestObject
        assert obj.d == 5
        obj = [1, 2, 3, 6, 's'] as TestObject
        assert obj.d == 6
    }
}

1

如果您计划使用地图,这里也有一些可以实现的内容(不使用 as):

class TestObject {
  private int a = 1
  protected int b = 2
  public int c = 3
  int d = 4
  String s = "s"
}

TestObject obj = [a: 1, b: 2, c: 3, d: 6, s: 's']

assert obj.a == 1 && obj.b == 2 && obj.c == 3 && obj.d == 6 && obj.s == 's'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接