Best way to “negate” an instanceof

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

    You can achieve by doing below way.. just add a condition by adding bracket if(!(condition with instanceOf)) with the whole condition by adding ! 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
    
    0 讨论(0)
  • 2021-01-30 02:39

    No, there is no better way; yours is canonical.

    0 讨论(0)
  • 2021-01-30 02:42

    I agree that in most cases the if (!(x instanceof Y)) {...} is the best approach, but in some cases creating an isY(x) function so you can if (!isY(x)) {...} is worthwhile.

    I'm a typescript novice, and I've bumped into this S/O question a bunch of times over the last few weeks, so for the googlers the typescript way to do this is to create a typeguard like this:

    typeGuards.ts

    export function isHTMLInputElement (value: any): value is HTMLInputElement {
      return value instanceof HTMLInputElement
    }
    

    usage

    if (!isHTMLInputElement(x)) throw new RangeError()
    // do something with an HTMLInputElement
    

    I guess the only reason why this might be appropriate in typescript and not regular js is that typeguards are a common convention, so if you're writing them for other interfaces, it's reasonable / understandable / natural to write them for classes too.

    There's more detail about user defined type guards like this in the docs

    0 讨论(0)
提交回复
热议问题