Has anyone written a user-defined Converter for the
org.apache.commons.beanutils package that works with
type-safe enumeration classes? It should be easy to
do, or even to write a converter generator.

Given

public class Suit {
    private String name;
    public final static Suit CLUBS    = new Suit("Clubs");
    public final static Suit DIAMONDS = new Suit("Diamonds");
    public final static Suit HEARTS   = new Suit("Hearts");
    public final static Suit SPADES   = new Suit("Spades");
    private Suit(String name) {this.name = name;}
}

I can easily write a Converter that uses a Map from
String to Suit:

public class SuitConverter implements Converter {
    private final static Map map = new HashMap();
    static {
        map.put(CLUBS.toString(),    CLUBS);     
        map.put(DIAMONDS.toString(), DIAMONDS);     
        map.put(HEARTS.toString(),   HEARTS);     
        map.put(SPADES.toString(),   SPADES);  
    }
    // Conversion methods follow.
}

It would be easier if I referred to the SuitConverter
inside Suit, but that would be poor engineering. I
would inflict the costs of having a SuitConverter on
all the clients, and many might not want to pay it.

However, I could use reflection to find all the
enumerants inside Suit, and create the map that way.
In pseudo-code, it would be:

public class SuitConverter implements Converter {
    private final static Map map = new HashMap();
    static {
        // For each field f in Suit which is
        //     public,
        //     final,
        //     static,
        //     of type Suit
        map.put(f.toString(), String);
    }
    // Conversion methods follow.
}

Still, I would need to write a separate SuitConverter class,
a ChessPieceConverter class, a BridgeDenominationConverter
class, and so on.  However, perhaps I could merge these all
into one.  After all, Suit.CLUBS != ChessPiece.KING.  The
conversion methods all return an Object.  Then, I would have

public class TypeSafeConverter implements Converter {
    private final static Map map = new HashMap();
    public static void register(Class tseClass) {
        // Analyze tseClass,
        // Insert mappings,
        // Register with ConverterUtils.
    }
    // Converter code.
}

If no one has done anything like this, and I haven't made a
gross error, I may do it myself.

I'm writing a Struts application, and I want to go from
String values for checkboxes and radio buttons to type-safe
enumerations in my business objects without converting by hand.

Respectfully,
Eric Jablow
Praxis Engineering Technologies, Inc.
301-490-4299 x. 131.



--
To unsubscribe, e-mail:   <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>

Reply via email to