getting Enum constant

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Gangreen
    New Member
    • Feb 2008
    • 98

    getting Enum constant

    I have the following enum.

    Code:
    **
     * An enum to represent types of mechanics.
     * 
     * @author 
     * @version 1.0
     */
    public enum Mechanics {
    	ISOLATION(0),
    	COMPOUND(1);
    	
    	/**
    	 * Variable to hold the value of the mechanics.
    	 */
    	private final int mechanics;
    	
    	/**
    	 * Constructor to create a mechanics
    	 * 
    	 * @variable	newMechanics
    	 * 				The value of the new mechanics
    	 */
    	Mechanics (int newMechanics) {
    		this.mechanics = newMechanics;
    	}
    	
    	/**
    	 * An inspector method that returns the value of the calling operation.
    	 * 
    	 * @return 	the value of the calling mechanics.
    	 * 			| result >= 0 && result < 2
    	 */
    	 public int getValue(){
    		 return mechanics;
    	 }
    	 
    	 /**
    	  * A method to check whether the value of a given mechanics
    	  * matches that of this mechanics
    	  * 
    	  * @variable	other
    	  * 			The mechanics to be compared with this mechanics
    	  */
    	 public boolean equals(Mechanics other){
    		 return this.getValue() == other.getValue();
    	 }
    }
    Now, I also have objects, which have a property that is a constant of this Enum. (isolation or compound). Now I am searching for a way of saving these objects (to textfiles), and loading them.

    Which means that the property of the object which is the enum should be saved in a way (i guess using the associated int) that is simple.

    Also I should be able to load this enum again. However I do not know how to do this, since a constructor of an enum is private, and the method that loads does not know wether the 0 or 1 stands for isolation or compound.

    How can I do this, without using switch-like things? I have much larger enums then the one I showed here.

    Thanks
  • BigDaddyLH
    Recognized Expert Top Contributor
    • Dec 2007
    • 1216

    #2
    Your enum is over-engineered ;-)

    The following in sufficient:

    [CODE=Java]public enum Mechanics {ISOLATION, COMPOUND};[/CODE]

    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:

    [CODE=Java]String s = m1.name(); //or m1.toString();
    Mechanics m2 = Mechanics.value Of(s);[/CODE]

    or convert it to its ordinal and back:

    [CODE=Java]int ord = m1.ordinal();
    Mechanics m2 = Mechanics.value s()[ord];[/CODE]

    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:

    [CODE=Java]public class SaveMe {
    private Mechanics mech;
    private int another;

    public SaveMe() {
    }

    public SaveMe(Mechanic s mech, int another) {
    setMechanics(me ch);
    setAnother(anot her);
    }

    public void setMechanics(Me chanics 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());
    }
    }[/CODE]

    Code:
    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:

    Code:
    <?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!

    Comment

    • Gangreen
      New Member
      • Feb 2008
      • 98

      #3
      I see. Damn I thought they weren't that easy.

      Thanx for everything!

      Comment

      • BigDaddyLH
        Recognized Expert Top Contributor
        • Dec 2007
        • 1216

        #4
        ps.

        There are times when it makes sense to add methods (even polymorphic methods) to an enumerated type, Check out the Planet and Operation examples:

        [http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html]

        Comment

        Working...