Java 8:class.getName()和String文字之间的区别 [英] java 8: difference between class.getName() and String literal

查看:221
本文介绍了Java 8:class.getName()和String文字之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理开关盒.

如果我们使用class.getName(),则出现如下错误:大小写表达式必须是常量表达式":

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目标的值必须是枚举值或(编译时)

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.

这篇关于Java 8:class.getName()和String文字之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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