如何在switch语句中将String转换为枚举?

Mor*_*ten 1 java enums switch-statement command-line-arguments

我有这个代码,我想接受命令行args fx"12 EUR"进行转换:

public class Main {

   enum Currency {EUR, USD, GBP,INVALID_CURRENCY;
   static final float C_EUR_TO_DKK_RATE = (float) 7.44;
   static final float C_USD_TO_DKK_RATE = (float) 5.11;
   static final float C_GBP_TO_DKK_RATE = (float) 8.44;
   static float result = 0;
   static int amount = 0;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Q1

        if (args.length == 2) {
            amount = Integer.parseInt(args[0]);
            String currencyIn = args[1].toString();

            Currency enumConversion = currencyIn; //**<---- HERE**
            switch (enumConversion) {
                case EUR:
                    result = amount * C_EUR_TO_DKK_RATE;
                    break;
                case USD:
                    result = amount * C_USD_TO_DKK_RATE;
                    break;
                case GBP:
                    result = amount * C_GBP_TO_DKK_RATE;
                    break;
                default:
                    result = 0;
                    break;
            }
            System.out.println((float) amount + " " + enumConversion + " converts to "
                + Math.round(result*100.0)/100.0 + " DKK");


        } else {
            System.out.println("Invalid arguments!");
            System.exit(1);
        }
    }

}
   }
Run Code Online (Sandbox Code Playgroud)

如何将String currencyIn转换为枚举,以便我可以在switch语句中使用args输入?

RHS*_*ger 6

javadocs中,有一种方法可用于执行此操作.

static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) 
Run Code Online (Sandbox Code Playgroud)

Currency enumConversion = Currency .valueOf(currencyIn); //**<---- HERE**
Run Code Online (Sandbox Code Playgroud)

作为随机附注,我几乎总是iValueOf在我的枚举中添加一个(即不区分大小写的版本)方法,以方便使用.