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

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

    Below code is self-explanatory, We can use an enum with a switch case:

    /**
     *
     */
    enum ClassNames {
        STRING(String.class, String.class.getSimpleName()),
        BOOLEAN(Boolean.class, Boolean.class.getSimpleName()),
        INTEGER(Integer.class, Integer.class.getSimpleName()),
        LONG(Long.class, Long.class.getSimpleName());
        private Class typeName;
        private String simpleName;
        ClassNames(Class typeName, String simpleName){
            this.typeName = typeName;
            this.simpleName = simpleName;
        }
    }
    

    Based on the class values from the enum can be mapped:

     switch (ClassNames.valueOf(clazz.getSimpleName())) {
            case STRING:
                String castValue = (String) keyValue;
                break;
            case BOOLEAN:
                break;
            case Integer:
                break;
            case LONG:
                break;
            default:
                isValid = false;
    
        }
    

    Hope it helps :)

提交回复
热议问题