Consider the following code:
Class Demo
{
Person person = new Person("foo"); // assume Person class has a 'name' field.
//Now, how do I get the value of a field, using some expression.
String expression = "person.name";
}
Now, I want to evaluate the ‘expression’ to get the value of the ‘name’ attribute. Can anyone tell how it can be done?
—
Updated: the ‘expression’ string I’ll be getting it from an XML file. So, will it be possible to use ‘Reflection’ in that scenario also? the ‘expression’ string may go into deeper levels also, like ‘person.birthday.date’.
There’s no native way in Java to do this. A variety of other options exist.
One approach is to use JXPath. This uses XPath-style syntax to query objects. It may be a little overkill for your purposes, but is undoubtedly powerful.
e.g. from the JXPath home page:
which asks the given vendor object for it’s address given a zip code of 90210. So you can navigate object hierarchies and provide predicates to perform ‘SELECT .. WHERE’ type queries.
See also this java.net article for more examples (shameless plug of something I wrote).