Re: Enum and variable problematics
Patricia Shanahan wrote:
jesperkn wrote:
....
In psedu code the following should happend:
For each variable XX in class struct do
{
System.out.println("name " + XX + " value " + XX.value())
}
Should print out the following:
name aa value 0
name bb value 0
name cc value 0
Is there an easier way to do this, than using enums?
Regards
Jesper
If you really need to do this, why not reflection? Use java.lang.Class
to get the Field[] for the fields you want to see. Use each Field
object's get() to obtain the value.
Patricia
Caveat, reflection in Java tends to over-complicate code.
Perhaps you should consider using an EnumMap instead of actual java fields.
public class DataLog {
enum FieldName {aa, bb, cc, dd}
List<FieldName> firstData = java.util.Arrays.asList(aa, bb, dd);
List<FieldName> secondDaata = java.util.Arrays.asList(aa, bb, cc);
Map<FieldName, String> data =
new EnumMap<FieldName, String>(FieldName.class);
public void set(List<FieldName> fields, String value) {
for (FieldName field: fields) {
set(field, value);
}
}
public void set(FieldName field, String value) {
data.put(field, value);
}
}
Much *much* cleaner than reflection.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>