gpt4 book ai didi

java - 从 Modelclass 层次结构的顶层调用 setter

转载 作者:行者123 更新时间:2023-12-01 18:16:13 24 4
gpt4 key购买 nike

假设您有一个模型类层次结构,例如

    public class TopLevel {
private MiddleLevel middleLevel = null;

public TopLevel() {
middleLevel = new MiddleLevel();
}

public MiddleLevel getMiddleLevel() { return middleLevel; }
}
    public class MiddleLevel {
private LowLevel lowLevel = null;

public MiddleLevel () {
lowLevel = new LowLevel();
}

public LowLevel getLowLevel() { return lowLevel; }
}
    public class LowLevel {
private Value value = null;

public LowLevel() {
value = new Value();
}

public Value getValue() { return value; }
}
    public class Value {
private String stringValue = "ItsAValue";
private String doubleValue = 1.0d;
private String integerValue = 4321;

public void setStringValue(String value) {
stringValue = value;
}
}

当然还有具有不同属性的其他类。例如。该层次结构由 Jaxb 创建并实例化。

现在,我想在值类中设置一个值。当然我可以执行类似的操作:

    TopLevel topLevel = new TopLevel();
topLevel.getMiddleLevel().getLowLevel().getValue().setStringValue("NewValue");

有没有办法简化或概括这一点,例如能够调用所有这些类对象的“路径”来设置内部的值?这是一些伪代码,我的意思是:

    public class Anotherclass {
public static void main(String[] args) {
TopLevel topLevel = new TopLevel();
setStringValueByPath("topLevel/middleLevel/lowLevel/value/stringValue", "newValue");
setDoubleValueByPath("topLevel/middleLevel/lowLevel/value/doubleValue", 5.0d);
setIntegerValueByPath("topLevel/middleLevel/lowLevel/value/integerValue", 1234);
}

}

非常感谢

亚历克斯

最佳答案

好吧,如果有人感兴趣,我想我找到了一个我一直在寻找的解决方案:

基于Java.reflection的递归方法:

public class ReflectionSetter {
private static List<Field> getFields(Object object) {
List<Field> fields = new ArrayList<>();
fields.addAll(Arrays.asList(object.getClass().getDeclaredFields()));
return fields;
}

private static Field hasField(Object object, String fieldName) {
for (Field f : getFields(object)) {
if (f.getName().equalsIgnoreCase(fieldName)) return f;
}
return null;
}

public static void setValue(Object object, String path, String newValue) throws IllegalArgumentException, IllegalAccessException {
if (path.contains("/")) {
int pos = path.indexOf('/');
String first = path.substring(0, pos);
String rest = path.substring(pos+1);
Field f = ReflectionSetter.hasField(object, first);
if (null == f) throw new IllegalArgumentException("Path not found: " + path);
f.setAccessible(true);
Object obj = f.get(object);
setValue(obj, rest, newValue);
} else {
Field f = ReflectionSetter.hasField(object, path);
if (f == null) throw new IllegalArgumentException("Field not found: " + path);
// if found -> set value
f.setAccessible(true);
f.set(object, newValue);
}
}
}

现在,您可以通过路径设置值。用法:

    TopLevel topLevel = new TopLevel();
ReflectionSetter.setValue(topLevel, "middleLevel/lowLevel/value/myValue", "NewValue");

关于java - 从 Modelclass 层次结构的顶层调用 setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60361864/

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