关于java:“否定” instanceof的最佳方法

Best way to “negate” an instanceof

我在想,是否存在一种更好/更巧妙的方法来否定Java中的instanceof
实际上,我正在执行以下操作:

1
if(!(str instanceof String)) { /* do Something */ }

但是我认为应该存在一种"美丽"的语法。

有谁知道它是否存在以及其语法如何?

编辑:
美丽地说,我可能会这样说:

1
if(str !instanceof String) { /* do Something */ } // compilation fails


不,没有更好的办法。你的是规范的。


我不知道您说"美丽"时的想法,但是那又如何呢?我个人认为这比您发布的经典表格差,但有人可能会喜欢...

1
if (str instanceof String == false) { /* ... */ }


您可以使用Class.isInstance方法:

1
if(!String.class.isInstance(str)) { /* do Something */ }

...但是它仍然被否定并且非常丑陋。


通常,您不只需要if,还需要else子句。

1
2
if(!(str instanceof String)) { /* do Something */ }
else { /* do something else */ }

可以写成

1
2
if(str instanceof String) { /* do Something else */ }
else { /* do something */ }

或者,您可以编写代码,这样就无需知道它是否为String。例如

1
if(!(str instanceof String)) { str = str.toString(); }

可以写成

1
str = str.toString();

如果您可以使用静态导入,并且您的道德准则允许

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ObjectUtils {
    private final Object obj;
    private ObjectUtils(Object obj) {
        this.obj = obj;
    }

    public static ObjectUtils thisObj(Object obj){
        return new ObjectUtils(obj);
    }

    public boolean isNotA(Class< ? > clazz){
        return !clazz.isInstance(obj);
    }
}

接着...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import static notinstanceof.ObjectUtils.*;

public class Main {

    public static void main(String[] args) {
        String a ="";
        if (thisObj(a).isNotA(String.class)) {
            System.out.println("It is not a String");
        }
        if (thisObj(a).isNotA(Integer.class)) {
            System.out.println("It is not an Integer");
        }
    }    
}

这只是一个流畅的界面练习,我绝对不会在现实生活中使用它!
以您的经典方式走,它不会混淆其他人阅读您的代码!


如果您觉得它更容易理解,则可以使用Java 8执行以下操作:

1
2
3
4
5
6
7
8
9
public static final Predicate<Object> isInstanceOfTheClass =
    objectToTest -> objectToTest instanceof TheClass;

public static final Predicate<Object> isNotInstanceOfTheClass =
    isInstanceOfTheClass.negate(); // or objectToTest -> !(objectToTest instanceof TheClass)

if (isNotInstanceOfTheClass.test(myObject)) {
    // do something
}


好的,只是我的两分钱,使用一个is字符串方法:

1
2
3
4
5
6
7
8
9
10
public static boolean isString(Object thing) {
    return thing instanceof String;
}

public void someMethod(Object thing){
    if (!isString(thing)) {
        return null;
    }
    log.debug("my thing is valid");
}

您可以通过以下方式来实现。.只需添加括号if(!(condition with instanceOf))来添加条件,并在开始时添加!运算符即可添加整个条件,就像下面的代码片段中提到的那样。

1
if(!(str instanceof String)) { /* do Something */ } // COMPILATION WORK

代替

1
if(str !instanceof String) { /* do Something */ } // COMPILATION FAIL