java - 有没有办法找出哪个 IF 条件 'triggered' 进入 if (){ } block ?

标签 java

在此示例中:

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/

相关文章:

java - 在 Windows 上使用 exec-maven-plugin 执行 shell 脚本

Java 将对象转换为字节数组的高效方法

java - 在 Inno Setup 中找到 JRE 安装路径

java - 为什么 Gson fromJson 抛出 JsonSyntaxException : Expected BEGIN_OBJECT but was BEGIN_ARRAY?

java - libGDX - 如果我播放声音,我的 Android 手机会口吃/有微延迟

java - 如何从客户端应用程序调用 weblogic 服务器中的集群 EJB 应用程序

java - 无法看到 ObjectAid UML Explorer 插件

java - 在 Applet 中嵌入 JFrame

java - 我在使用 netbeans 时收到此错误 pls 00103

java - ivyDE 的替代品