You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@velocity.apache.org by Cédric CHAMPEAU <ce...@lingway.com> on 2007/05/23 12:56:28 UTC

Java 5 Enums and data access

Hi,

I am facing a problem when trying to use Java 5 enums as parameters to 
getters in a velocity template. Obviously, Velocity does not seem to 
manage it correcty. I'd like to be able to write something like :

$person.get(Title) where Java code would be person.get(PersonEnum.Title)

To acheive that, the only way I've found is to expose an enum wrapper 
which allows me to retrieve enum values. The problem is that I would 
have to do that for each enum in my application which is not optimal. 
Here's a sample code which explains my solution. I'm not sure there's 
any better way, since I can't find any documentation about that :

public class VelocityEnumProblem {

    public static void main(String[] args) {
        try {
            Velocity.init();
            VelocityContext ctx = new VelocityContext();
            EnumMap<MyEnum,String> container = new EnumMap<MyEnum, 
String>(MyEnum.class);
            container.put(MyEnum.ONE, "something to store");
            ctx.put("container", container);
            ctx.put("MyEnum", new MyEnumWrapper());
            PrintWriter pout = new PrintWriter(System.out);
            Velocity.evaluate(ctx, pout, "test", 
"$container.get($MyEnum.ONE) ");
            pout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class MyEnumWrapper {
        public MyEnum get(String name) {
            return MyEnum.valueOf(name);
        }
    }

    public enum MyEnum {
        ONE,
        TWO,
        THREE
    }

}