Using @EnumValue in own code

516 views
Skip to first unread message

Dominik Dorn

unread,
Nov 25, 2011, 6:23:20 PM11/25/11
to Ebean ORM
I have a enum annotated with some @EnumValue's.

Ebean does a good job mapping Integers returned from my DB to the
correct enum.
For my webapp, I'd like to use the same Annotations to map the
Integers I get from there
to the correct enum, but from looking through the Ebean source, I
can't really figure out how.
It seems, its somehow done in
trunk/src/main/java/com/avaje/ebeaninternal/server/type/
DefaultTypeManager.java
but I'm not sure how to use that in my code.

What I'm actually looking for is something like

Integer value = 1110; // value supplied by user or other data source
(json/xml/flat file)
MYENUMTYPE type = parseEnum(MYENUMTYPE.class, value);


also a way to easily deserialize the value would be nice, like

Object value = deserialize(type);

Is there a way to do this with existing Ebean code?

Thanks,
Dominik

Dominik Dorn

unread,
Nov 25, 2011, 6:51:22 PM11/25/11
to Ebean ORM
Nevermind, already figured it out. If this code is not available anywhere,
I think it might be good to create a small Utility helper class people can use?


Here's the code, (public domain)

public <T extends Enum<T>> T parseEnum(Class<T> type, Object value)
{
for(Field f : type.getDeclaredFields())
{
EnumValue enumValue = f.getAnnotation(EnumValue.class);
if(enumValue != null)
if(enumValue.value().equals(String.valueOf(value)))
return Enum.valueOf(type, f.getName());
}
return null;
}

Thanks for this great project!


Dominik

--
Dominik Dorn
http://dominikdorn.com
http://twitter.com/domdorn

Skripten, Mitschriften, Lernunterlagen, etc. findest Du auf
http://www.studyguru.eu !

Reply all
Reply to author
Forward
0 new messages