final public static ints can't be used in a switch statement?

落花浮王杯 提交于 2019-12-23 20:35:19

问题


I'm confused. The following code has errors ("..." represents elided code):

int byteOrder = ...;
switch (byteOrder)
{
    case HDF5Constants.H5T_ORDER_BE:
        return ByteOrder.BIG_ENDIAN;
    ...
}

The error is on the case statement and Eclipse complains "case expressions must be constant expressions". I looked in the source file for this and it has a long list of lines like this:

final public static int H5T_ORDER_BE = H5.J2C( JH5T_ORDER_BE );

I thought you could use final public static int constants as cases in a switch statement. Am I wrong???


回答1:


From what you've shown H5T_ORDER_BE is not a compile-time constant (which it needs to be) - it's evaluated at runtime during the initialisation of the class. If it evaluated to a constant such as 123 (rather than what appears to be a static method call) then the compiler wouldn't complain.




回答2:


You are wrong! :-)

Case statements can refer only to constants. A static variable is initialized at runtime, so it can't be used here.



来源:https://stackoverflow.com/questions/1155409/final-public-static-ints-cant-be-used-in-a-switch-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!