Re: Enum and variable problematics
On 11 Feb., 18:11, jesperkn <jespe...@gmail.com> wrote:
On 10 Feb., 21:34, Daniel Pitts
<newsgroup.spamfil...@virtualinfinity.net> wrote:
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 fiel=
ds.
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/>- Skjul =
tekst i anf=F8rselstegn -
- Vis tekst i anf=F8rselstegn -
Again, thanks for the respons. I have approximately 30-40 variables
that I get from an XML string - I know the names and the types of the
variables (since I have designed the XML string) so I have no problem
with making a class with the correct variables and types.
-- XML string --
<data>
<entry>
<name>peter</name>
<age>24years</age>
</entry>
<entry>
<name>Lea</name>
<age>31years</age>
</entry>
</data>
-- XML string --
class xmldata ()
{
String name;
String Age;
}
Now when I browse down my XML tree I want to set store the variables
that I "meet", in my xmldata class - programatically naturally. I like
the idea of the enumMap, but I guess that my Java is a bit rusty.
Could you please elaborate on this?
If I used getters/setters wouldn't I have to have one getter/setter
for each variable that I have?
Using reflection is definitely going accross the river to get water
since I know what variables I would expect.
Regards
Jesper- Skjul tekst i anf=F8rselstegn -
- Vis tekst i anf=F8rselstegn -
Hi Daniel
I just read your post one more time, and now it makes sense. The
enumMap is a great solution.
Thanks!
Regards
Jesper