微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在关注使用列表和地图作为构造函数this博文.

为什么以下列表无法强制反对

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,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.String)
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '[1,java.lang.String)
    at in.ksharma.Test.main(Test.groovy:22)

解决方法

你可以使用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
    }
}

马上就会考虑清单.

编辑

嗯..我不确定列表是否可行.仅当您添加适当的构造函数时.
完整样本:

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,s:'s'] as TestObject
        assert obj.d == 5
        obj = [1,6,'s'] as TestObject
        assert obj.d == 6
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐