Best way to “negate” an instanceof

后端 未结 9 1431
后悔当初
后悔当初 2021-01-30 02:01

I was thinking if there exists a better/nicer way to negate an instanceof in Java. Actually, I\'m doing something like:

if(!(str instanceof String))         


        
9条回答
  •  半阙折子戏
    2021-01-30 02:35

    ok just my two cents, use a is string method:

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

提交回复
热议问题