• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to use instanceof operator in loop  RSS feed

 
Suddewar Ramulu
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Every one,

I am facing the problem with instanceof operator. Actually I want to check an object for instance of more than 20 classes.
Please could you let me know is there any short cut to write this logic in loop.

here is the code example.


if(obj instanceof Class1){

} else if(obj instanceof Class2){

} else if(obj instanceof Class3){

}.... and so on.


Sorry, the example code was wrong

the actual requirement will be as follows.


if(obj instanceof Class1 || obj instanceof Class2 || obj instanceof Class3 || ...){

//doing some thing.

}


Thanks
Rams











Thanks
Rams




 
Jiafan Zhou
Ranch Hand
Posts: 193
Fedora Linux Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although I believe this question is not related to the architect certification, using the visitor pattern is a good way of displacing the instanceof checks. Especially you are doing a lot of instanceof checking. Imagine the object is defined in the last instanceof check, then it is likely to be a performance hit.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no shortcut to that logic, but if you find yourself performing a lot of instanceof checks that's often a sign that the design can be improved - e.g. to use some polymorphic behaviour of the classes instead.
 
Paul Clapham
Sheriff
Posts: 22841
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jiafan Zhou wrote:Although I believe this question is not related to the architect certification...


Neither do I. Let's move it to a better forum.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Welcome to the Ranch, Suddewar Ramulu.

This kind of code indicates that your code is not very object-oriented. Instead of having a long chain of if - else if statements where you are checking the types of objects, consider inventing an interface that contains the method(s) you need to call on the objects, and then use polymorphism to call the appropriate method in the class. So, for example, instead of this:

Do something like this:

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!