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)) { /* do Something */ }
But I think that a "beautiful" syntax to do this should exist.
Does anyone know if it exists, and how the syntax look like?
EDIT: By beautiful, I might say something like this:
if(str !instanceof String) { /* do Something */ } // compilation fails
Using the Not InstanceOf in Java The instanceof returns a Boolean value, so negating it will return the false value. Negating the InstanceOf is done similarly to other negating in Java.
The primary alternative to using instanceof is polymorphism. Rather then ask which type of object you have at the current position you tell the object, whatever it is, to do what you want done. If both objects know how to do that then this works fine, even if they do it differently.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. Its syntax is. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
No, there is no better way; yours is canonical.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With