Accessing class/attributes from string

Do you mean look them up by value? Or do you mean iterate over all fields without naming them? If the second, Table has TableRow, and it will do just what you want – you can dump the whole table or the whole row without naming each of the fields.

If you have a custom class and are constantly adding fields to it, then just write a class method.

savefiledata = books[0].savedata();

Now when you add/change/delete your class attributes, update the class savedata() method (if they are attributes that you want to save). This keeps your interface to your field collection in one place, rather than scattered all over.

Another approach: say that your class potentially has hundreds of fields, and those fields are ad-hoc, or even user-generated per-object. You feel like you can’t possibly enumerate them all. You could manage them like this:

class book {
  String title;
  StringDict s;
  IntDict i;
}

Now you can search for if you book has a field, add a field, delete a field, or dump all the fields (whatever they are).

/**
 * Class fields in Dicts
 * 2019-08 Processing 3.4
 * discourse.processing.org/t/accessing-class-attributes-from-string/13583/2
 */

void setup() {
  Book mybook = new Book("mybook");
  mybook.i.set("catalogue", 200);
  mybook.i.set("foo", 700);
  mybook.f.set("bar", 9.95);
  mybook.s.set("baz", "qwerty");
  
  println("\nretrieve by name:");
  if (mybook.i.hasKey("catalogue")){
    println(mybook.i.get("catalogue"));
  }
  
  println("\nlist all fields:");
  mybook.printFields();
}

class Book {
  String title;
  FloatDict f;
  IntDict i;
  StringDict s;
  Book(String title){
    this.title = title;
    this.f = new FloatDict();
    this.i = new IntDict();
    this.s = new StringDict();
  }
  void printFields(){
    for (String key : this.f.keys()) {
      println(key, this.f.get(key));
    }
    for (String key : this.i.keys()) {
      println(key, this.i.get(key));
    }
    for (String key : this.s.keys()) {
      println(key, this.s.get(key));
    }
  }
  void saveData(){
    // list and iterate over fields here for saving
  }
}

If that doesn’t help, can you give a concrete example of what you are trying to do?

1 Like