Richard Poole
Richard Poole

Reputation: 591

access java object variable dynamically

I'm very new to Java and Android development.

I have a case where I need to populate an object with data from an XML document. Some of the node names in the XML are not standardised in any way, so I have created a HashMap where the key is the node name, and the value is the variable it needs to be assigned to.

In PHP the code would look something like (in basic terms):

$array = new Array("somenodename" => "firstname", "someothernodename" => "lastname");
$object = new Person();
$object->{$array['somenodename']} = "Whatever the XML node value was";

In Java I have gotten as far as:

From the object I need to populate:

public String firstname;
public String lastname;

public static Map getHashMap(){
    Map<String, String> map = new HashMap<String, String>();
    map.put("somenodename", "firstname");
    map.put("someothernodename", "lastname");

    return map;
}

From the class populating the object assuming the somenode and someothernode are dymanic:

Person person;
Map personMap = person.getHashMap();
if( personMap.containsKey("somenodename") ){
    person.[personMap.get("somenodename")] = "James";
}
if( personMap.containsKey("someothernodename") ){
    person.[personMap.get("someothernodename")] = "Bond";
}

Is there anyway of assigning a value to an class variable where the variable name is... variable?

Upvotes: 1

Views: 1242

Answers (1)

micha
micha

Reputation: 49552

It's called Reflection

Assume you want to call the method myMethod(String s) from Person:

Person p = new Person();
Class<Person> clazz = p.getClass();
Method m = clazz.getMethod("myMethod", String.class);
m.invoke(p, "my string argument");

Upvotes: 2

Related Questions