gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:08:42 25 4
gpt4 key购买 nike

我正在关注 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, 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)

最佳答案

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

关于java - 如何将 Groovy 列表强制转换为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24033829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com