java三元组,没有赋值的Java三元组

Is there a way to do a java ternary operation without doing an assignment or way to fake the assingment?

I like how succinct ternary code looks when doing a bunch of if/then/elses.

I'm hoping to be able to call one of two void functions based on a boolean algebra statement.

Something like:

(bool1 && bool2) ? voidFunc1() : voidFunc2();

My functions are of return type void, so if there is a way to fake this in an assignment to make it work, then I"m okay with that... I would like to see how to do it though :)

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值