Java reflect Field get class variables

Hello, i want to load all variables from sketch and want to check some variables in the specific class and do some changes, how i can get class from Field ? :neutral_face::thinking:

import java.lang.reflect.Field;

testClass test = new testClass(125); // save some number, wich we want to edit or read/write

void setup() {
  println(test); // only chech if return "toString" is good
  
  final Class <?extends PApplet> c = getClass(); // read all variables

  final Field[] fields = c.getDeclaredFields(); // get it to the array

  int x = fields[0].i; // <-- I dont know hot to load the class "test" and get var "i", can you help me ?

  // HOW TO GET FIELD CLASS NAME LIKE A "testClass" ?
  // ... AND after that load list of variables in the class and get someone or rewrite to this variable some other number..

  exit();
}

class testClass { // class for test
  int i = 0;
  testClass(int i) {
    this.i = i;
  }
  String toString() {
    return "This is class, iam returning some string...";
  }
}

Thanks, George.

1 Like

Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/reflect/Field.html#get(java.lang.Object)

import java.lang.reflect.Field;

final TestClass test = new TestClass((int) random(1000));

void setup() {
  final Class<TestClass> c = TestClass.class;
  final Field[] fields = c.getDeclaredFields();

  printArray(fields);
  println();

  try {
    for (final Field f : fields) println(f.get(test));
  } 
  catch (final ReflectiveOperationException e) {
    throw new RuntimeException(e);
  }

  exit();
}

class TestClass {
  int i;

  TestClass(int ii) {
    i = ii;
  }

  String toString() {
    return str(i);
  }
}
2 Likes

THANKS, but can i get this class withou inserting “test” object for Getting class ?

  • A class itself is merely a description for fields, methods & constructors.
  • Non-static fields only got values stored in them after a class is instantiated.
  • Therefore, we’ve gotta have an instance of a class prior to use the reflective method Field::get().
4 Likes