开发者

how to set Enum from configuration

I'm reading configuration from an xml file. I have a property called linkType in my configuration. I have equivalent enum class in my project which declares two types of link.

How can I set enum type from String? if I read EMPTY from configuration and if I have linkType.EMPTY declared enum how will I set this to EMPTY?

Because further in my code I have a s开发者_如何学Pythonwitch statement on this enum but I can't set it from configuration


Sounds like you're looking for Enum.valueOf.

(Sorry about the imprecise link, can't get the space in the URL to work.)


All enums have a static method valueOf(string) that returns an instance of the enum if the string matches an member of the enum.


If you use XML for configuration anyways you could use InPUT. You would define the valid values in a design space descriptor:

<SParam id="linkType">
    <SChoice id="EMPTY"/>
    <SChoice id="NON_EMPTY"/>
    ...
</SParam>

In a code mapping descriptor you decide how this maps to your code:

<Mapping id="linkType" type="my.package.linkType"/>
<Mapping id="linkType.EMPTY" type="EMPTY"/>
<Mapping id="linkType.NON_EMPTY" type="NON_EMPTY"/>
...

Finally, in your configuration (say, "config.xml"), you write:

<SValue id="linkType" value="EMPTY"/>

InPUT takes care of the Enum treatment. From your code you call:

Design input = new Design("config.xml");
LinkType lt = input.getValue("linkType");

For a single parameter you would probably not make the effort. But if you have many properties, and you want to make sure that only certain values can be taken, InPUT might be an option.

A side note: according to convention, enum "linkType" should be called "LinkType".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜