【问题标题】:How to get a class selected by the user?如何获取用户选择的课程?
【发布时间】:2019-03-19 05:53:52
【问题描述】:

我已经阅读了一些关于它的帖子,但不确定是否有一些是我一直在寻找的答案。我想通过用户输入选择一个类并检查它是否在列表中。我不想创建 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;
}

【问题讨论】:

    标签: java class inheritance


    【解决方案1】:

    使用Class.isInstance 检查您拥有的对象是否类的实例。

    你的支票应该是:

    if(classDefinedByUser.isInstance(geo))
    

    请注意,如果geo == null,此方法将返回false(即使它应该是类的实例)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-17
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-10
      • 1970-01-01
      相关资源
      最近更新 更多