开发者

HashMap and case construct

For readability reasons I'm trying to avoid using Char based case constructs, using Java 6. I cannot switch to 7 jet...

Map<String, String> map = new HashMap<String, String>() {
    {
        put("foo", "--foo");
                put("bar), "--bar");
        ... 
    }
    private static final long serialVersionUID = 1L; // java problem
};

The serialVersionUID - as far as I know, maybe part of the problem. Currently I'm working with if constructs:

if (!map.containsValue(args[0])) {
    logger.error("Unknown parameter:  "开发者_开发技巧 + args[0]);
        ...

I handle ~ 30 parameters. In any case a growing number.

Is it even possible to define switch constructs with enums or HashMaps In Java 6?


If you're handling over 30 parameters in the same way, then you need some kind of loop. For example:

for (int i=0; i<args.length; i++)
{
   String param = args[i];
   if (!map.containsValue(param))
      logger.error("Unknown parameter:  " + param);
   .. handle argument
}

It looks like you are parsing command line arguments. There are some good libraries available that offer flexible command line parsing, for example args4j. With args4j, you create your data model, and let it map fields in the data to command line arguments.


Using Strings in a switch statement will be available in Java 7.

For moderate or complex parsing of command line arguments I strongly recommend using Commons-CLI, it provides a great API to make this much easier for you to handle. An example of it's usage:

// create Options object
Options options = new Options();

// add t option
options.addOption("t", false, "display current time");
...

CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse( options, args);

if(cmd.hasOption("t")) {
    // print the date and time
}
else {
    // print the date
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜