Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to "negate" an instanceof

Tags:

java

syntax

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 
like image 219
caarlos0 Avatar asked Jan 30 '12 17:01

caarlos0


People also ask

How to negate instanceof Java?

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.

How do I stop Instanceof?

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.

What is instanceof in Java?

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 .


1 Answers

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

like image 60
maerics Avatar answered Sep 21 '22 17:09

maerics