Your enum is over-engineered ;-)
The following in sufficient:
- public enum Mechanics {ISOLATION, COMPOUND};
There is no need to define a "value" property as you did. Enum defines a property
ordinal that does the same thing. Enum also overrides toString, equals, hashCode and clone correctly. Enums implements Serializable and Comparable as well.
To save and restore an enum, you can convert it to a String and back:
- String s = m1.name(); //or m1.toString();
-
Mechanics m2 = Mechanics.valueOf(s);
or convert it to its ordinal and back:
- int ord = m1.ordinal();
-
Mechanics m2 = Mechanics.values()[ord];
As mentioned, enums are serializable so you could save and restore objects with enum fields that way, but java beans can be persisted with XMLEncoder/Decoder as well:
- public class SaveMe {
-
private Mechanics mech;
-
private int another;
-
-
public SaveMe() {
-
}
-
-
public SaveMe(Mechanics mech, int another) {
-
setMechanics(mech);
-
setAnother(another);
-
}
-
-
public void setMechanics(Mechanics mech) {
-
this.mech = mech;
-
}
-
-
public Mechanics getMechanics() {
-
return mech;
-
}
-
-
public void setAnother(int another) {
-
this.another = another;
-
}
-
-
public int getAnother() {
-
return another;
-
}
-
-
public String toString() {
-
return String.format("[mech=%s, another=%d]",
-
getMechanics(), getAnother());
-
}
-
}
- import java.beans.*;
-
import java.io.*;
-
-
public class EnumTest {
-
public static void main(String[] args) throws IOException {
-
testParse();
-
testIO();
-
}
-
-
static void testParse() {
-
String[] input = {"ISOLATION","COMPOUND"};
-
for(String s : input) {
-
Mechanics m = Mechanics.valueOf(s);
-
System.out.format("%s --> %s, with ordinal %d%n", s, m, m.ordinal());
-
}
-
}
-
-
static void testIO() throws IOException {
-
File file = new File("test.xml");
-
-
XMLEncoder e = new XMLEncoder(
-
new BufferedOutputStream(
-
new FileOutputStream(file)));
-
e.writeObject(new SaveMe(Mechanics.COMPOUND, 17));
-
e.close();
-
-
XMLDecoder d = new XMLDecoder(
-
new BufferedInputStream(
-
new FileInputStream(file)));
-
Object result = d.readObject();
-
d.close();
-
System.out.println(result);
-
}
-
}
The method testIO create the file test.xml:
- <?xml version="1.0" encoding="UTF-8"?>
-
<java version="1.6.0" class="java.beans.XMLDecoder">
-
<object class="SaveMe">
-
<void property="another">
-
<int>17</int>
-
</void>
-
<void property="mechanics">
-
<object class="Mechanics" method="valueOf">
-
<string>COMPOUND</string>
-
</object>
-
</void>
-
</object>
-
</java>
-
Conclusion: enums are simpler and easier to use than you first thought!