Best way to “negate” an instanceof

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

    Usually you don't want just an if but an else clause as well.

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

    can be written as

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

    Or you can write the code so you don't need to know if its a String or not. e.g.

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

    can be written as

    str = str.toString();
    

提交回复
热议问题