Java Ternary without Assignment

Nope you cannot do that. The spec says so.

The conditional operator has three operand expressions. ? appears
between the first and second expressions, and : appears between the
second and third expressions.

The first expression must be of type boolean or Boolean, or a
compile-time error occurs.

It is a compile-time error for either the second or the third operand
expression to be an invocation of a void method.

[EDIT]

Since you asked about reflection, here’s a solution. I’m not recommending this. I’m posting it only because you asked.

public class MyCall
{

    public void a(){System.out.println("a");}
    public void b(){System.out.println("b");}

    public static void main(String... args)
    {
        new MyCall().go();
    }

    public void go()
    {
        Class<? extends MyCall> class1 = this.getClass();
        Method aMethod = class1.getMethod("b", null);
        Method bMethod = class1.getMethod("a", null);
        Object fake = false ? aMethod.invoke(this, null) : bMethod.invoke(this, null);
        Object fake2 = true ? aMethod.invoke(this, null) : bMethod.invoke(this, null);
    }
}

At the end of the day you’ve got to ask yourself if being succint improves your code’s readability (think for-each loop). None of these solutions improve the code’s readability IMHO. If I were you I’d rather go with this.

if(condition)
    a();
else
    b();

I’m actually for including braces even when loops only contain a single line, but since you’re going after crisp code, the snippet above should do.

Leave a Comment