Java switch statement: Constant expression required, but it IS constant

前端 未结 13 1803
予麋鹿
予麋鹿 2020-11-22 10:42

So, I am working on this class that has a few static constants:

public abstract class Foo {
    ...
    public static final int BAR;
    public static final          


        
13条回答
  •  广开言路
    2020-11-22 11:10

    I recommend using the following way:

    public enum Animal {
        DOG("dog"), TIGER("tiger"), LION("lion");
        private final String name;
    
        @Override
        public String toString() {
            return this.name;
        }
    }
    
    
    public class DemoSwitchUsage {
    
         private String getAnimal(String name) {
             Animal animalName = Animal.valueOf(name);
             switch(animalName) {
             case DOG:
                 // write the code required.
                 break;
             case LION:
                 // Write the code required.
                 break;
             default:
                 break;
             }
         }
    }
    

提交回复
热议问题