我读过一些关于它的帖子,但不确定其中是否是我一直在寻找的答案。我想通过用户输入选择一个类并检查它是否在列表中。我不想创建 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;
}
最佳答案
使用Class.isInstance
检查您拥有的对象是否是类的实例。
您的支票应该是:
if(classDefinedByUser.isInstance(geo))
请注意,如果geo == null
,此方法将返回false
(即使它应该是该类的实例)
关于java - 如何获取用户选择的类(class)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55234461/