0

I have a Java program which uses the ENUM to encode different strings. Now, I'm adding the Main class which takes in input from the command line some parameters. The problem is that the user input is a string, but the ENUM type is a different java object. Here the code:

public static void main(String[] args) {

    if(args.length!=3)
    {
        printUsage();
        System.exit(0);
    }

    File dbpath = new File( args[0] );
    File file= new File( args[1] );
    String query = args[2];
    Result res = manager.executeQuery(QuerySelector.MYQUERY);

As you can see, there is no way that the 3rd argument query can match the argument of executeQuery, since it's a QuerySelector not a String. I want that the user just need to type "MYQUERY" which is a string (in this case, but there are countless), and find a way to insert it into the executeQuery argument. Could you please suggest a convenient approach?

Wall
  • 293
  • 3
  • 13
  • You can use `Enum.valueOf(QuerySelector.class, query)` where query/arg[1] is your input string argument but make sure you provided valid input argument which is exist as a enum constant in `QuerySelector` otherwise it will throw : > **IllegalArgumentException** if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type – Irfan Bhindawala Oct 03 '18 at 10:16

1 Answers1

2

You can create a method in your enum to convert your string to corresponding enum.

public static QuerySelector forName(String query) {
    for (QuerySelector param : QuerySelector.values()) {
        if (query.equals(param.toString()))) {
            return param;
        }
    }
    return null;
}

Then use it to your call

Result res = manager.executeQuery(QuerySelector.forName(query));
Deb
  • 2,922
  • 1
  • 16
  • 32
  • I think this approach is almost correct, but it doesn't work for me. Because the user is type the name of one of the variables listed in the ENUM, but the comparison of this function is with the values. – Wall Oct 03 '18 at 10:38
  • 1
    I solved it using param.name() during the comparison. – Wall Oct 03 '18 at 10:48