Serialization and deserialization

But it seems I’ve got no class “Field”. What do I have to import to get this class?

Yup. In API you can always find package for class.

Your code snippet does not work in my environment

Sorry, my bad. If you are getting class from instance - you should use data.getClass(). If you are using class - then use static field in it DataClass.class.

Another one thing. If you declare classes in you sketch file (*.pde) - they will have reference to your sketch instance. I suppose you don’t need it. Just create new tab as .java file.

Here it is:

sketch.pde:

import java.lang.reflect.Field;

DataClass data = new DataClass();
data.x = 100;
data.y = 500;

Field[] fields = data.getClass().getDeclaredFields();
// or DataClass.class.getDeclaredFields();

try {
  for (Field field : fields) {
      System.out.println(field.getType() + " " + field.getName() + " = " + field.get(data));
  }
} catch (IllegalAccessException e) {
  e.printStackTrace();
}

DataClass.java:

public class DataClass {
    int x;
    int y;
    String title="hello world!";
}

Checkout documentation for Reflection if you decided to go this way. It’s good as exercise but to get things done I suggest you to implement Externalizable. :slight_smile:

1 Like