本文主要是介绍JDK之Enumeration,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
源码
package java.util;/*** @author Lee Boynton* @since JDK1.0*/
public interface Enumeration<E> {boolean hasMoreElements();E nextElement();
}
Enumeration的遍历
Spring之ContextCleanupListener源码
package org.springframework.web.context;import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;import org.springframework.beans.factory.DisposableBean;public class ContextCleanupListener implements ServletContextListener {private static final Log logger = LogFactory.getLog(ContextCleanupListener.class);@Overridepublic void contextInitialized(ServletContextEvent event) {}@Overridepublic void contextDestroyed(ServletContextEvent event) {cleanupAttributes(event.getServletContext());}static void cleanupAttributes(ServletContext sc) {Enumeration<String> attrNames = sc.getAttributeNames();// 测试此枚举是否包含更多的元素while (attrNames.hasMoreElements()) {// 如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素。String attrName = attrNames.nextElement();if (attrName.startsWith("org.springframework.")) {Object attrValue = sc.getAttribute(attrName);if (attrValue instanceof DisposableBean) {try {((DisposableBean) attrValue).destroy();}catch (Throwable ex) {logger.error("Couldn't invoke destroy method of attribute with name '" + attrName + "'", ex);}}}}}}
相关源码
- org.apache.catalina.core.ApplicationContext.getAttributeNames()方法
@Override
public Enumeration<String> getAttributeNames() {Set<String> names = new HashSet<>();names.addAll(attributes.keySet());return Collections.enumeration(names);
}
- java.util.Collections.enumeration(Collection)方法
public static <T> Enumeration<T> enumeration(final Collection<T> c) {return new Enumeration<T>() {private final Iterator<T> i = c.iterator();public boolean hasMoreElements() {return i.hasNext();}public T nextElement() {return i.next();}};
}
这篇关于JDK之Enumeration的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!