Search code examples
javaenumsargs

Java matching string input as ENUM


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?


Solution

  • 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));