开发者

Java switch constant expression... Is there any clever way to get this to compile?

开发者 https://www.devze.com 2023-03-24 04:59 出处:网络
I\'m returning to Java dev after many years away from it. Is there anyway to get this code to compile?

I'm returning to Java dev after many years away from it. Is there anyway to get this code to compile?

class Mpeg4
    {
    public static final int FourCC2Int(char aA, char aB, char aC, char aD)
        {
        return (aA << 24) | (aB << 16) | (aC << 8) | (aD);
        }

    public static void main(String aArgs[]) throws Exception
        {
        int x = Integer.parseInt(aArgs[0]);

        switch (x)
          开发者_开发知识库  {
            case Mpeg4.FourCC2Int('f', 't', 'y', 'p'): // This won't be reduced by the compiler to a constant.
                // doSomething();
                break;

            }
        }
    }

I tried also to have a class constant such as

class Mpeg4
    {
    private static final int KFtyp = Mpeg4.FourCC2Int('f', 't', 'y', 'p');

    public static void main(String aArgs[]) throws Exception
        {
        int x = Integer.parseInt(aArgs[0]);

        switch (x)
            {
            case KFtyp: // Foiled again.
                // doSomething();
                break;
            }
        }
    }

The language has changed quite a bit, and I've done Googling. Is there any way I can keep my code tidy i.e. not manually reducing the 'macro' or having a potentially massive if-then-else-if block? Maybe compiler optimisation flags might be one route? I find this situation quite lame.


You could do this

    switch (x) {
    case ('f' << 24) | ('t' << 16) | ('y' << 8) | ('p'): 
        // doSomething();
        break;
    }

Here is the JLS on what can go in a constant expression thats part of the case. Turns out its pretty flexible.

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313


switch needs compile-time constant expressions (of integral or enum types, from Java 7 on also strings) for the cases, and the result of a method call is not a compile-time constant. (The compiler will not call your method.)

If you only need a single (or a low number of) case block, use an if instead.

If you have a large number, you could think about using a HashMap or such with the Command pattern. Or let some other program generate your code (e.g. if you are writing a parser).


Nope - the value must be constant at compile time. KFtyp is constant at class load time.

Java7 has some relief for you in this regards. ( String comparison will be allowed in switches. )

However, a switch with a long series of checks against a single variable is one of the least useful constructs. Invariably, a interface with different implementors or a super class with subclasses that defines the correct behavior by construction is the better choice.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号