Please compile and run this example. Please read step by step comments to understand what I expect to achieve from this sample program.
import java.util.*; import java.lang.reflect.*; //I first create a simple local class class MyClass1 { public Double aDouble1; public Double aDouble2; public MyClass1() { aDouble1 = 250.0; aDouble2 = -100.9; } } public class Identifier { public static void main(String [] args) { //OK. I create an instance of MyClass1 MyClass1 m1 = new MyClass1(); //Then I get the runtime Class of that object Class<?> that = m1.getClass(); //Then I get all the declared fields of that object Field [] fields = that.getDeclaredFields(); //I define an Object array to the size of Field array Object[] fieldsAsObjects = new Object[fields.length]; //Now I get each Field object into the Object array try { for (int next = 0; next < fields.length; next++) { fieldsAsObjects[next] = fields[next].get(m1); } } catch(Exception exp) { exp.printStackTrace(); } //Since now I have fields of m1 object in the array, I go change //then to a new value (or rather make them zeros). for (int next = 0; next < fieldsAsObjects.length; next++) { fieldsAsObjects[next] = 0.0; } //Afterwards I EXPECT THE m1.aDouble1 and m1.aDouble2 to be changed //to 0.0. But it is not happpening. Why and how to? System.out.println(m1.aDouble1); System.out.println(m1.aDouble2); } }