JSTL - 使用 forEach 迭代用户定义的类 [英] JSTL - Using forEach to iterate over a user-defined class

查看:36
本文介绍了JSTL - 使用 forEach 迭代用户定义的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向自定义 Java 类添加哪些方法,以便可以迭代其中一个成员中的项目?我找不到任何关于 JSTL forEach 标记实际工作方式的规范,所以我不确定如何实现.

What methods do I need to add to a custom Java class so that I can iterate over the items in one of its members? I couldn't find any specifications about how the JSTL forEach tag actually works so I'm not sure how to implement this.

例如,如果我创建了一个通用的ProjectSet"类并且我想在 JSP 视图中使用以下标记:

For example, if I made a generic "ProjectSet" class and I woud like to use the following markup in the JSP view:

<c:forEach items="${projectset}" var="project">
...
</c:forEach>

基本类文件:

public class ProjectSet {
    private ArrayList<Project> projects;
    public ProjectSet() {
        this.projects = new ArrayList<Project>();
    }
    // .. iteration methods ??
}

是否有任何我必须实现的接口,如 PHP 的 ArrayAccessIterator 才能使其工作?

Is there any interface that I must implement like PHP's ArrayAccess or Iterator in order for this to work?

不直接访问 ArrayList 本身,因为我可能会使用某种使用泛型的 Set 类,并且 JSP 视图不必知道该类的内部工作原理.

Without directly accessing the ArrayList itself, because I will likely be using some sort of Set class using generics, and the JSP view shouldn't have to know about the inner workings of the class.

推荐答案

Iterable 接口提供了这个功能:

The Iterable interface provides this functionality:

public class ProjectSet implements Iterable<Project> {
    private ArrayList<Project> projects;
    public ProjectSet() {
        this.projects = new ArrayList<Project>();
    }

    // .. iteration methods ??
   @Override
   public Iterator<Project> iterator() {
       return projects.iterator();
   }
}

您可以根据需要交换迭代器逻辑.

You can exchange the iterator logic as you need.

这篇关于JSTL - 使用 forEach 迭代用户定义的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆