I have two classes. The first class has someField which the second class needs to change, so the first class calls FirstClass.setSomeField(value). The second class can not change the field at that moment, so it stores this FutureChange into a list which it will go through at a later time and apply the necessary changes. The class must store it in a way that it can compare instances of FutureChange, i.e. to avoid setting the same field twice, and other things.
What is the best way to implement FutureChange? With reflection, this is easy. The problem is that I will have hundreds of classes, each class with many fields.
I even tried a map, with a switch for field names:
public class Example {
public static Integer number;
public static String words;
public static void main(String args[]) {
Map<Field, Object> map = new HashMap<Field, Object>();
// store modifications
map.put(Field.number, new Integer(10));
map.put(Field.words, "Words");
// some time later
for(Map.Entry<Field, Object> entry: map.entrySet()) {
modify(entry.getKey(), entry.getValue());
}
}
public static void modify(Field m, Object value) {
switch(m){
case number:
number = (Integer) value;
break;
case words:
words = (String) value;
break;
}
}
public enum Field {
number,
words;
}
}
But this isn’t the most effective way, and could get clogged up as the classes get larger. Anyone know how to best implement this?
Some more code:
public class Main {
FirstClass a = new FirstClass();
SecondClass b = new SecondClass();
// Third, Fourth, etc.
public static void main(String args[]) {
while(true) {
// run each, no modifications allowed
a.run(); // may want to modify several variables of b
b.run(); // same as above
// end of all runs, now modify
a.modifyAll();
b.modifyAll();
}
}
}
As you can see, I must store it during the runs, and execute later.
Storing anonymous inner Callable and calling later would be perfect, but I need to examine what it is doing so that I can compare two and determine whether they are conflicting.
I would use reflections as you suggested. This is going to be much slower than applying the changes directly. If you really want efficiency, you are better off breaking your code into two phases/stages one which uses the current value and one which applies the changes rather than trying to store the changes.