Skip to main content

Enums and fromValue

2 replies [Last post]
bobc
Offline
Joined: 2005-04-13

I just ported my project over to JAXB 2.0 to try it out. I have the 20050407 RI, and for the most part everything seems to be going good, and 2.0 fixed a lot of my annoyances with 1.0.4.

One problem I am having relates to enums. (I am new to Java 1.5 so if I am missing anything obvious let me know.) In my app I am manually creating a JAXB object tree then marshalling it to XML. I have to get the enum represented by the value I have as a string. I can't use valueOf() to get at the proper enum class, because I have the value instead of the constant name, and the name might be changed to meet Java naming requirements (e.g. if the string is "1" the constant will be named "_1"). According to the spec, it looks like a fromValue() method is supposed to be generated in the enum class to support this use case, but I don't have one. Am I reading that right, and does the RI do that yet? I can post a schema excerpt if needed.

-Bob

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
kohsuke
Offline
Joined: 2003-06-09

Hmm.

There's always a tension between generating less code and being more user-friendly. And in this case I think we made a concious decision not to generate the fromValue method.

The reason why fromValue is difficult is because it has to work with typed values, which could like 'int' and 'float'. In 2.0, we can't generate code that relies on any particualr runtime, this is particularly hard.

One change in the spec which is not implemented yet is not to convert the case of enum constant names. This was proposed for different reasons, but I guess that improves the chance of that the Enum.valueOf method works.

bobc
Offline
Joined: 2005-04-13

Alright, that makes sense. I can work around it with a map, just means a little more work :)

Thanks,
Bob