简体   繁体   中英

Java switch constant expression… Is there any clever way to get this 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 ie 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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM