• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

140
Views
Best way to "negate" an instanceof

I was thinking if there exists a better/nicer way to negate an instanceof in Java. Actually, I'm doing something like:

if(!(myObject instanceof SomeClass)) { /* 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(myObject !instanceof SomeClass) { /* do Something */ } // compilation fails
about 3 years ago · Santiago Trujillo
3 answers
Answer question

0

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

about 3 years ago · Santiago Trujillo Report

0

I don't know what you imagine when you say "beautiful", but what about this? I personally think it's worse than the classic form you posted, but somebody might like it...

if (str instanceof String == false) { /* ... */ }
about 3 years ago · Santiago Trujillo Report

0

You could use the Class.isInstance method:

if(!String.class.isInstance(str)) { /* do Something */ }

... but it is still negated and pretty ugly.

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error