Why “final static int” can be used as a switch's case constant but not “final static

后端 未结 5 2107
遥遥无期
遥遥无期 2021-02-12 13:21

Why is this int switch valid:


public class Foo {
    private final static int ONE = 1;
    private final static int TWO = 2;

    public static void main(String         


        
5条回答
  •  Happy的楠姐
    2021-02-12 13:42

    I had a similar requirement and worked around this problem by switching on the Enums ordinal number instead of switching on the enum itself. This is not very beautiful/intuitive but it works:

    public class Foo {
    
        private final static int SRC = 0; // == RetentionPolicy.SOURCE.ordinal();
        private final static int RT = 2; // == RetentionPolicy.RUNTIME.ordinal();
    
        static{
            if (RT != RetentionPolicy.RUNTIME.ordinal() || SRC !=  RetentionPolicy.SOURCE.ordinal()) {
                throw new IllegalStateException("Incompatible RetentionPolicy.class file");
            }
        }
    
        public static void main(String[] args) {
            RetentionPolicy value = RetentionPolicy.RUNTIME;
            switch (value.ordinal()) {
                case RT: break;
                case SRC: break;
            }
        }
    
    }
    

    Note that it is of course not possible to declare the constant as e.g.

    private final static int SRC = RetentionPolicy.SOURCE.ordinal();
    

    for the same reason one is not able to declare the constant as an Enum in the first place...

提交回复
热议问题