How to force a Groovy list into an object?

I follow this on my blog about using lists and maps as constructors.

Why can't the following list force an 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)
+4
source share
2 answers

You can use the card:

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

Think about the list in a minute.

EDIT

Hmm .. I'm not sure if this is possible with a list. Only if you add the 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
    }
}
+5
source

If you plan to use the card instead, here is something (without using as) that you can implement:

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'
+1
source

Source: https://habr.com/ru/post/1543186/


All Articles