简体   繁体   English

如何将变量参数传递给instanceof?

[英]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? 我正在寻找一种方法将参数c传递给instanceof,因为我需要循环遍历代码中显示的数组,但编译器返回错误“unknown class c”如何解决这个问题?

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. 我知道我可以使用a.getClass()。getSimpleName()并检查它是否等于字符串数组中的元素,但我想更好地理解如何使用关键字instanceof及其工作原理。

You don't - the instanceof operator always takes the name of a type as its second operand. 您没有 - instanceof 运算符始终将类型的名称作为其第二个操作数。 However, you can use the Class.isInstance method instead: 但是,您可以使用Class.isInstance 方法

bool = c.isInstance(a);

Note the lack of an if/else - any time you have if (condition) return true; else return false; 注意缺少if / else - if (condition) return true; else return false;任何时间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. 但是,在当前代码中,循环后bool的值将仅取决于数组的最后一个元素,因为您在每次迭代时都重新分配它。

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.) (使用Java 8,你可以使用streams和anyMatch来做到这anyMatch ,但这是另一回事。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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