【问题标题】:How do I access an object method inside a List?如何访问 List 中的对象方法?
【发布时间】:2014-07-25 00:27:54
【问题描述】:

我正在使用 jsp 创建一个网站。我有一个方法可以将JDBC 查询中的每一行作为对象返回。每个对象都被添加到一个列表中并返回到 jsp 文件中。

这是返回存储在 MySQL 数据库中的类别列表的方法:

public List<Object> getCategories() throws Exception{
    this.catList = new ArrayList<Object>();

    try{
        sql = "SELECT cat_id, cat_name FROM crm_categories";
        prep = conn.prepareStatement(sql);
        rs = prep.executeQuery();
        while(rs.next()){
            cat = new Category();
            cat.setAttributes(rs.getInt("cat_id"), rs.getString("cat_name"));
            this.catList.add(cat);
        }
    } catch(Exception e){
        e.printStackTrace();
    }
    return catList;
}

Category 对象如下所示:

@WebServlet("/Category")
public class Category extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String name;
    private int id;

    public Category() {
        name        = null;
        id          = 0;
    }

    public void setAttributes(int id, String name){
        this.name       = name;
        this.id         = id;
    }

    public String[] getAttributes(){
        String[] attributes = {this.name, String.valueOf(this.id)};
        return attributes;
    }
}

我试图遍历对象列表。它将“测试”打印到浏览器 7 次,这是正确的类别数:

dbCon conn          = new dbCon();
List<Object> catList;

// get a list of all categories
catList = conn.getCategories();
for (Object o : catList){
    out.println("test");
}

如何访问每个类别getAttributes 方法?

【问题讨论】:

    标签: java mysql jsp loops object


    【解决方案1】:

    问题是您的getCategories 方法返回List&lt;Object&gt;,而返回List&lt;Category&gt; 更有意义:

    public List<Object> getCategories() throws Exception{
        // Note: this is now a *local* variable. There was no need for it to be an
        // instance variable as far as I can see.
        // If you're using Java 7 or higher, you can use new ArrayList<>(); too.
        List<Category> catList = new ArrayList<Category>();
        ...
    }
    

    然后:

    for (Category category : conn.getCategories()) {
        out.println(Arrays.toString(category.getAttributes()));
    }
    

    【讨论】:

    • 这项工作感谢乔恩。还有你关于局部变量的注释 - 我想我理解所有变量都应该在类的顶部声明并在构造函数中给出一个默认值,然后再用于 1 个或多个方法?你是说如果一个变量只在一个方法中使用,那么它应该在那个方法中声明?
    • @crm:好吧,除非您需要将该值作为对象状态的一部分持久化。您需要了解不同类型的变量:docs.oracle.com/javase/tutorial/java/nutsandbolts/…
    【解决方案2】:

    如果你想访问Category类型的方法,你必须有另一个声明:

    dbCon conn = new dbCon();
    List<Category> catList = conn.getCategories();
    for (Category cat : catList) {
        // here you can access "cat.getAttributes()"
    }
    

    当然,这需要你更改方法dbCon.getCategories()

    public List<Category> getCategories() throws Exception{
        this.catList = new ArrayList<Category>();
        ...
        return catList;
    }
    

    catList 显然是一个字段,这也必须更改。

    【讨论】:

      【解决方案3】:
      public List<Category> getCategories() throws Exception{
          List<Category> tmp= new ArrayList<Category>();
      
          try{
              sql = "SELECT cat_id, cat_name FROM crm_categories";
              prep = conn.prepareStatement(sql);
              rs = prep.executeQuery();
              while(rs.next()){
                  cat = new Category();
                  cat.setAttributes(rs.getInt("cat_id"), rs.getString("cat_name"));
                  tmp.add(cat);
              }
          } catch(Exception e){
              e.printStackTrace();
          }
          this.catList = tmp;
          return tmp;
      }
      

      已发布正确答案,但我想指出,you should not use class field 在此方法中。如果同时在两个线程中启动此方法,则会导致某些 DB 条目加倍(在某些情况下所有条目都会加倍)。

      使用本地字段,如果此方法需要修改类字段,请在返回结果之前进行。

      访问对象当然是

      for (Category c: getCategories()) {
          c.getAttributes();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-26
        • 1970-01-01
        • 1970-01-01
        • 2013-08-22
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        相关资源
        最近更新 更多