简体   繁体   English

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

[英]How to coerce Groovy list into object?

I'm following this blog post about using Lists and Maps as Constructors. 我下面这个博客张贴有关使用列表和地图的构造函数。

Why does following list fail to coerce to object? 为什么以下列表无法强制反对?

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
    }
}

I get this exception: 我得到这个例外:

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)

You can use map: 你可以使用map:

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
    }
}

Will think about list in a moment. 马上就会考虑清单。

EDIT 编辑

Hmm.. I'm not sure if it's possible with list. 嗯..我不确定列表是否可行。 Only if You add an appropriate constructor. 仅当您添加适当的构造函数时。 Full sample: 完整样本:

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
    }
}

If you plan to use map instead, here is something as well (without using as ) which can be implemented: 如果您打算使用map,那么也可以使用以下内容(不使用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'

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

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