Question

What I need is the following:

Person p = new Person();
Command.set(p, "person.name", "William");
//After that method call in line above, p.getName() should return "William"

And I needed set method as generic as possible, that is, not only a person parameter but any ValueObject I wanted. I began working on this algorithm using reflection but I'm not sure if that will fit and it's giving a lot of work. I wonder if there is anything already done, such as a framework in Java.

Thanks in advance!

Was it helpful?

Solution

Take a look at PropertyUtilsBean from Apache Commons Beanutils (http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.1/apidocs/org/apache/commons/beanutils/PropertyUtilsBean.html#setProperty%28java.lang.Object,%20java.lang.String,%20java.lang.Object%29 ).

Should be as simple as:

Person p = new Person();
PropertyUtils.setProperty(p, "name", "William");

Library supports setting nested properties as well, e.g.

PropertyUtils.setProperty(p, "address.street", "Route 69");
// equivalent of p.getAddress().setStreet("Route 69")

OTHER TIPS

It does look a little bit like what Dozer does. However dozer is for mapping class A into class B. For example this dozer mapping:

<mapping>
  <class-a>org.dozer.vo.deep.SrcDeepObj</class-a>
  <class-b>org.dozer.vo.deep.DestDeepObj</class-b>

  <field>
    <a>srcNestedObj.src1</a>
    <b>dest1.firstObj.secondObj.destVar</b>
  </field>
</mapping>

is the equivalent of:

destinationObject.getDest1().getFirstObj.getSecondObj.setDestVar(inputObject.getSrcNestedObj().getSrc1());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top