为什么“最终静态int”可以用作开关的常数,而不是“最终静态”,你的枚举“ [英] Why "final static int" can be used as a switch's case constant but not "final static <your enum>"

查看:103
本文介绍了为什么“最终静态int”可以用作开关的常数,而不是“最终静态”,你的枚举“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个int开关有效:

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[] args) {
        int value = 1;
        switch (value) {
            case ONE: break;
            case TWO: break;
        }
    }

}

枚举开关不是:


import java.lang.annotation.RetentionPolicy;

public class Foo {
    private final static RetentionPolicy RT = RetentionPolicy.RUNTIME;
    private final static RetentionPolicy SRC = RetentionPolicy.SOURCE;

    public static void main(String[] args) {
        RetentionPolicy value = RetentionPolicy.RUNTIME;
        switch (value) {
            case RT: break;
            case SRC: break;
        }
    }

}

我知道在这种情况下,必须是一个常量,所以为什么我可以使用一个final static int作为常量,而不是final static<你的枚举>?

I know that what goes in the case must be a constant, so why can I use a "final static int" as constant but not a "final static <your enum>"?

推荐答案

因为case语句标签必须有编译时常数或EnumConstantName。 JLS 14.11

Because a case statement label must have either a compile time constant or an EnumConstantName. JLS 14.11

编译时间常数只能是字符串和原始类型,如 JLS 15.28 。因此,您不能使用静态的最终<您的枚举>,因为它既不是编译时常数也不是枚举的名称。

Compile time constants can only be strings and primitive types, as described by JLS 15.28. Thus you can not use a static final <your enum>, as it is neither a compile time constant, nor the name of an enum.

这篇关于为什么“最终静态int”可以用作开关的常数,而不是“最终静态”,你的枚举“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆