2012-01-30 89 views
262

我在想如果存在一種更好/更好的方式來否定Java中的instanceof。 其實,我做這樣的事情:「否定」實例的最佳方法

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

但是,我認爲,應該存在一個「美麗」的語法來做到這一點。

有人知道它是否存在以及語法如何?


編輯: 美麗的,我可能會說這樣的事情:

if(str !instanceof String) { /* do Something */ } // compile failure 
+16

我恨'instanceof'的優先規則如此之多...... – luiscubal 2012-01-30 17:38:54

+4

你總是可以創建一個變量,像'boolean strIsString = str instanceof String;'... – vaughandroid 2012-01-30 17:42:11

+0

是啊@Baqueta,是一個選項。但是,在一種語法或另一種語法中,內存使用會發生什麼差異? – caarlos0 2012-01-30 20:04:03

回答

207

沒有,有沒有更好的辦法;你的規範。

+0

是的,好像。謝謝。 – caarlos0 2012-01-30 21:55:36

42

你可以使用Class.isInstance方法:

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

...但它仍然是否定和很醜陋。

+4

稍微好一點,多餘的括號會使代碼變得醜陋,恕我直言。 – caarlos0 2012-01-30 18:02:42

+0

這不是很慢嗎? – maxammann 2013-08-02 20:54:25

+4

這有不同的行爲。 instanceof關鍵字包含子類,方法不包含,您需要使用Class.isAssignableFrom複製行爲。 – 2014-02-04 17:11:05

15

通常,您不僅需要if,還需要else子句。

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

可以寫成

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

或者,您可以編寫代碼,所以你不需要知道它的一個字符串或沒有。例如

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

可以寫成

str = str.toString(); 
84

我不知道,當你說「美麗」你想象一下,但怎麼樣呢?我個人認爲它比你張貼的經典造型差,但有人可能會喜歡它......

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

仍然難看,則此方法返回true,我將編輯該問題..請稍等.. – caarlos0 2012-01-30 19:17:18

+16

+1爲可行的替代 – hidralisk 2012-06-25 01:54:29

+11

雙邏輯傷害我的頭:) – rogerdpack 2014-02-04 17:13:41

12

如果你可以使用靜態導入,和你的道德準則允許他們

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

然後。 ..

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

這只是一個流利的界面練習,我從來沒有使用過現實生活中的代碼!
尋找你的經典方式,它不會混淆讀取你的代碼的任何人!

+0

我不喜歡靜態進口..無論如何謝謝你嘗試幫助:) – caarlos0 2012-01-30 19:19:10

+5

+1爲迂迴代碼 – hidralisk 2012-06-25 01:52:44

2

OK只是我的兩分錢,使用是字符串方法:

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

或者簡單的if-else ...

if (str instanceof String) { 
} else { 
    // Your code, please. 
} 
+1

他想否定'(str instanceof字符串)'。這種方式違背了編程規律。 – 2017-10-21 15:33:09

-1

這有什麼錯

if (!(x instanceof y)) { 
}