views:

93

answers:

3

Hi!

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?

+1  A: 

I think this question has some answers which might help you

Peter Tillemans
A: 

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
}
matt b
+1  A: 

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.

mdma