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

前端 未结 13 1794
予麋鹿
予麋鹿 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:11

    Sometimes the switch variable can also make that error for example:

    switch(view.getTag()) {//which is an Object type
    
       case 0://will give compiler error that says Constant expression required
    
       //...
    }
    

    To solve you should cast the variable to int(in this case). So:

    switch((int)view.getTag()) {//will be int
    
       case 0: //No Error
    
       //...
    }
    

提交回复
热议问题