Best way to “negate” an instanceof

后端 未结 9 1325
后悔当初
后悔当初 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:18

    If you can use static imports, and your moral code allows them

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

    And then...

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

    This is just a fluent interface exercise, I'd never use that in real life code!
    Go for your classic way, it won't confuse anyone else reading your code!

提交回复
热议问题