在此示例中:
if (object instanceof SomeThing || object instanceof OtherThing) {
System.out.println("this block was entered because of: " + **____** )
}
我可以检查真实条件是SomeThing 还是OtherThing 吗?
编辑:我试图避免条件分离。
谢谢。
最佳答案
将这两种情况下的所有常见步骤重构为一个函数,然后:
if (object instanceof SomeThing) {
// It's SomeThing
System.out.println("Got here because it's SomeThing");
commonStuff();
}
else if (object instanceof OtherThing) {
// It's OtherThing
System.out.println("Got here because it's OtherThing");
commonStuff();
}
重新编辑:
edit: I'm trying to avoid the separation of conditions.
然后您有以下选择:
if (object instanceof SomeThing || object instanceof OtherThing) {
System.out.println("Got here because it's " +
(object instanceof SomeThing) ? "SomeThing" : "OtherThing")
);
}
或者
boolean isSomeThing:
if ((isSomeThing = object instanceof SomeThing) || object instanceof OtherThing) {
System.out.println("Got here because it's " +
isSomeThing ? "SomeThing" : "OtherThing")
);
}
关于java - 有没有办法找出哪个 IF 条件 'triggered' 进入 if (){ } block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17487610/