“否定”實例的最佳方法

本文翻譯自:Best way to “negate” an instanceof

I was thinking if there exists a better/nicer way to negate an instanceof in Java. 我在想是否存在一種更好/更巧妙的方法來否定Java中的instanceof Actually, I'm doing something like: 實際上,我正在執行以下操作:

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

But I think that a "beautiful" syntax to do this should exist. 但是我認爲應該存在一種“美麗”的語法。

Does anyone know if it exists, and how the syntax look like? 有誰知道它是否存在以及其語法如何?


EDIT: By beautiful, I might say something like this: 編輯:美麗,我可能會這樣說:

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

#1樓

參考:https://stackoom.com/question/c32U/否定-實例的最佳方法


#2樓

ok just my two cents, use a is string method: 好的,只是我的兩分錢,使用一個is字符串方法:

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");
}

#3樓

If you find it more understandable, you can do something like this with Java 8 : 如果您覺得它更容易理解,則可以使用Java 8執行以下操作:

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
}

#4樓

You can achieve by doing below way.. just add a condition by adding bracket if(!(condition with instanceOf)) with the whole condition by adding ! 您可以通過以下方式實現。.只需通過添加括號if(!(condition with instanceOf))和添加整個條件的條件來添加條件! operator at the start just the way mentioned in below code snippets. 首先按照下面的代碼片段中提到的方式操作運算符。

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

instead of 代替

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

#5樓

No, there is no better way; 不,沒有更好的辦法。 yours is canonical. 你的是規範的。


#6樓

You could use the Class.isInstance method: 您可以使用Class.isInstance方法:

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

... but it is still negated and pretty ugly. ...但是它仍然被否定並且非常醜陋。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章