We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › how to dynamically access data within a class
Page Index Toggle Pages: 1
how to dynamically access data within a class (Read 399 times)
how to dynamically access data within a class
Aug 25th, 2009, 5:41am
 
Hi,

Here's my problem:
I'm trying to load XML data in order to recreate the objects in my program.

Loading is fine. But when I want to write the data in the object, instead of manually assign every variable separately, I'd prefer to do something like that :
Code:
for (int j = 0; j < numAttributes; j++)
   {
     XMLElement attribute = souvenir.getChild(j);
     String attributeName = attribute.getName();

     souvenirPool[i].'attributeName' = attribute.getContent();

So it would automatically select the attribute to be initialized.

and here I have no clue about the syntax to do this kind of thing, I don't event know if it's possible... Undecided

any idea ?
is there any preexistent class to import xml objects ?

thanks in advance...
Re: how to dynamically access data within a class
Reply #1 - Aug 25th, 2009, 6:34am
 
You can do that with java.lang.reflect.

Quote:
HashMap values = new HashMap();
values.put("myParam1", 10);
values.put("myParam2", 12);

class MyClass {
  public int myParam1;
  public int myParam2;
  void check() {
    println(myParam1);
    println(myParam2);
  }
}

MyClass myObject = new MyClass();
java.lang.reflect.Field[] fields = myObject.getClass().getFields();
for (int i = 0; i < fields.length; i++) {
  Integer value = (Integer) values.get(fields[i].getName());
  try {
    fields[i].setInt(myObject, value.intValue());
  } catch (Exception e) {
  }
}
myObject.check();



Link to the Javadoc:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Field.html
Page Index Toggle Pages: 1