Question

I have a class something like below

public class ParentDTO
{
    private String name;
    private List<Child> childs;
    .... getters and setters
}

I want to get the Nth child name from an expression.

String sQuery ="childs[0].name";

Now I want to get name of that child from the parent DTO object

public String getChildName(ParentDTO paretnDTO, String query)
{
    // will return first child name when I pass 
    // query as sQuery
    // please help to implement
}
Était-ce utile?

La solution

(As requested by @Jason in comment, and as OP seems have done his responsibilities of study, here is an answer which give a bit more detail)

There are two main approaches we can take, both are similar in some aspects:

Approach 1: Java Bean Properties

If you know that the POJO object you are inspecting is a Java Bean (at least contains proper getters/setters for its properties), there are quite some Java Bean Utils that you can make use of, some of them even provides an extended syntax to navigate Bean Properties. Apache Common BeanUtils is an example:

// syntax not checked, just base on my memory. It should be close though.
String child0name = BeanUtils.getProperty(parentDto, "children[0].name");

Approach 2: Expression Language

If you are going to deal with a more complicated expression, or the object you deal with is not a strict bean (for example, you need to call a method of that object), then you may consider using an expression language engine. There are quite a lot of choice, SpEL and MVEL are two of them.

Normally these expression language can provide what bean utils can provide, like:

String child0name = Mvel.eval("children[0].name", parentDto);
// or if you want to call the method and do some more complicated expression,
// you can do it:
String child0name = Mvel.eval(
        "children[0].title + ' ' + children[0].constructFullName()", 
        parentDto);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top