Java 自动实例化对象并为给定路径设置值

Java 自动实例化对象并为给定路径设置值,java,reflection,javabeans,apache-commons-beanutils,Java,Reflection,Javabeans,Apache Commons Beanutils,我想通过嵌套Java对象结构中的给定路径字符串设置值。 如果集合属性不存在,则该属性应自动实例化: public class A { List<B> bs; // getter/setter } public class B { String b1; String b2; // getter/setter } public Object setValueForPath(String path, Object value){

我想通过嵌套Java对象结构中的给定路径字符串设置值。 如果集合属性不存在,则该属性应自动实例化:

public class A {

    List<B> bs;

    // getter/setter
}

public class B {

    String b1;

    String b2;

    // getter/setter
}


public Object setValueForPath(String path, Object value){

     // magic starts
     // Set Value for Path
     // automatically instantiate Objects if nessesary 

}

A result = setValueForPath("bs[0].b1", "test") // return full Object structure
assertEqual(result.getBbs().get(0).getB1(), "test");
公共A类{
名单b;
//吸气剂/塞特
}
公共B级{
b1串;
字符串b2;
//吸气剂/塞特
}
公共对象setValueForPath(字符串路径,对象值){
//魔术开始了
//设置路径的值
//如果需要,自动实例化对象
}
A result=setValueForPath(“bs[0].b1”,“test”)//返回完整的对象结构
assertEqual(result.getBbs().get(0.getB1(),“test”);

如何解决此问题?

您可以使用OGNL的序列运算符
来完成此操作,但这确实会使OGNL表达式更难读取

A a = new A()
Ognl.setValue("bs.add(0, new com.full.qualified.package.B()), bs[0].b1" a, "test")
assertEquals("test", a.getBbs().get(0).getB1())

您应该看看Apache commons OGNL: