使用 forName 和 Class.forName 和 isInstance

Use of forName and Class.forName and isInstance

我想将 class 的名称作为打印方法中的参数传递。 例如:public void printAll(String className) 我还创建了一个动物列表。 我只想打印属于 class 且名称为 className.

的节点

我试过使用这样的东西:

node tmp;
if (Class.forName(className).isInstance(tmp.getValue())

有什么帮助吗?

您可以将 class 名称比较为刺:

if (className.equals(tmp.getValue().getClass().getName()) {
    // do something
}

你可以使用这样的东西:

if (tmp.getValue.getClass().isInstance(Class.forName(className).newInstance())) { 
      //do something
}