A pit of the day: Constant expression required: Java's switch selection enumeration problem

insert image description here

A pit of the day: Constant expression required: Java's switch selection enumeration problem

When using Switch, the switch object is a common type, but when the case object is a method function called by an enumeration object, as shown below: Error:
insert image description here
insert image description here
Constant expression required

Solution: Use the enumeration object as the switch object, case enumeration object:
insert image description here
define the method in the enumeration class:

    /**
     * 提前判断,用于解决
     * Case中出现的Constant expression required
     * @param value 数值
     * @return 返回一个常数
     */
    public static DataSourceEnum getValue(int value){
    
    
        for(DataSourceEnum x:values()){
    
    
            if(x.getDataSourceCode()==value){
    
    
                return x;
            }
        }
        return null;
    }

Then test like this in the test:
insert image description here
Is it okay, cheating

Guess you like

Origin blog.csdn.net/qq_44918802/article/details/126629202