我已经阅读了一些有关它的文章,但不确定是否是我一直在寻找的答案。我想通过用户输入选择一个类,并检查它是否在列表中。我不想创建if,switch或Map(我将使用很多类)。如果可能的话,我正在尝试以几行代码执行此操作。谢谢!
public boolean isClassDefined(ArrayList<GeometricObject> geoObjects) {
Class<?> classDefinedByUser=null;
try {
classDefinedByUser = Class.forName("Square");
//as if user has typed "Square", being "class Square extends GeometricObject"
} catch (ClassNotFoundException ex) {
Logger.getLogger(Mission.class.getName()).log(Level.SEVERE, null, ex);
}
for (GeometricObject geo : geoObjects) {
//here is where i don't know what to do
//I want to create a if to check if there is an object (of the class
//defined by the user) initialized into ArrayList "geoObjects"
//I don't want to use lots of ifs
if (geo instanceof classDefinedByUser.getClass()) {
//if exists a Square type object, return true
return true;
}
}
return false;
}
答案 0 :(得分:1)
使用Class.isInstance
检查您拥有的对象 是否是类的实例。
您的支票应为:
if(classDefinedByUser.isInstance(geo))
请注意,如果false
,该方法将返回geo == null
(即使它应该是该类的实例)