java 8:class.getName() 和字符串字面量之间的区别

我正在研究开关盒.

如果我们使用 class.getName(),那么,我得到的错误是case 表达式必须是常量表达式",如下所示:

If we use class.getName(), then, I am getting error that "case expressions must be constant expressions" as follows:

switch(param.getClass().getName())
    {
        case String.class.getName():
            // to do
            break;
    }

即使我们执行以下操作,将字符串类名放入常量中,也会出现同样的错误:

Even if we do following, take string class name in a constant, then also, getting same error:

public static final String PARAM_NAME = String.class.getName();
switch(param.getClass().getName())
    {
        case PARAM_NAME:
            // to do
            break;
    }

但是,如果我执行以下操作,使用字符串文字java.lang.String",则不会出现错误:

But, if I do following, use the string literal "java.lang.String", there is not error:

public static final String PARAM_NAME = "java.lang.String";

谁能解释一下,为什么不接受前两个案例并接受最后一个案例?提前致谢.

Can anybody please explain this, why its not taking first two cases and taking the last one? Thanks in advance.

推荐答案

classObject.getName() 是方法调用,方法调用的结果根据定义不是编译时常量.字符串文字是一个编译时常量.

classObject.getName() is a method call, and the results of method calls are by definition not compile-time constants. A string literal is a compile-time constant.

请注意,虽然许多情况下可以将 static final 引用作为程序生命周期的常量,但 switch 必须在编译时对其选项进行硬编码-时间.case 目标的值必须是枚举值或(编译时)ConstantExpression.

Note that while many situations could take a static final reference as a constant for the lifetime of the program, a switch has to have its options hard-coded at compile-time. The value of a case target must be either an enum value or a (compile-time) ConstantExpression.

相关文章