简体   繁体   中英

How do I pass a variable argument to instanceof?

I am looking for a way to pass the argument c to instanceof, because i need to loop through an array like shown in the code, but the compiler returns the error "unknown class c" How do I fix this?

Class0 a = new Class0();
boolean bool;
Class[] array = new Class[]{Class0.class, Class1.class};
for(Class c : array){
   if(a instanceof c)
       bool = true;
   else
      bool = false;
}

I know I could use a.getClass().getSimpleName() and check if it's equal to an element in an array of Strings, but I'd like to understand better how to use the keyword instanceof and how it works.

You don't - the instanceof operator always takes the name of a type as its second operand. However, you can use the Class.isInstance method instead:

bool = c.isInstance(a);

Note the lack of an if/else - any time you have if (condition) return true; else return false; if (condition) return true; else return false; or the like, you can collapse it. However, in your current code, the value of bool after the loop will only depend on the last element of the array, as you're reassigning it on every iteration.

You may actually want:

boolean bool = false;
for (Class c : array){
   if (c.isInstance(a))
       bool = true;
   }
}

(With Java 8 you could do that using streams and anyMatch , but that's a different matter.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM