01: /*
02: * Copyright (c) 2002-2003 by OpenSymphony
03: * All rights reserved.
04: */
05: package com.opensymphony.webwork.util;
06:
07: import java.lang.reflect.Array;
08: import java.util.*;
09:
10: /**
11: * MakeIterator.
12: * <p/>
13: * Taken from WebWork 1.x by:
14: *
15: * @author <a href="hermanns@aixcept.de">Rainer Hermanns</a>
16: * @version $Id: MakeIterator.java 2371 2006-03-11 17:09:33Z davsclaus $
17: */
18: public class MakeIterator {
19:
20: /**
21: * Determine whether a given object can be made into an <code>Iterator</code>
22: *
23: * @param object the object to check
24: * @return <code>true</code> if the object can be converted to an iterator and
25: * <code>false</code> otherwise
26: */
27: public static boolean isIterable(Object object) {
28: if (object == null) {
29: return false;
30: }
31:
32: if (object instanceof Map) {
33: return true;
34: } else if (object instanceof Collection) {
35: return true;
36: } else if (object.getClass().isArray()) {
37: return true;
38: } else if (object instanceof Enumeration) {
39: return true;
40: } else if (object instanceof Iterator) {
41: return true;
42: } else {
43: return false;
44: }
45: }
46:
47: public static Iterator convert(Object value) {
48: Iterator iterator;
49:
50: if (value instanceof Iterator) {
51: return (Iterator) value;
52: }
53:
54: if (value instanceof Map) {
55: value = ((Map) value).entrySet();
56: }
57:
58: if (value == null) {
59: return null;
60: }
61:
62: if (value instanceof Collection) {
63: iterator = ((Collection) value).iterator();
64: } else if (value.getClass().isArray()) {
65: //need ability to support primitives; therefore, cannot
66: //use Object[] casting.
67: Object a = Array.newInstance(value.getClass()
68: .getComponentType(), (Array.getLength(value)));
69: ArrayList list = new ArrayList(Array.getLength(value));
70:
71: for (int j = 0; j < Array.getLength(value); j++) {
72: list.add(Array.get(value, j));
73: }
74:
75: iterator = list.iterator();
76: } else if (value instanceof Enumeration) {
77: Enumeration enumeration = (Enumeration) value;
78: ArrayList list = new ArrayList();
79:
80: while (enumeration.hasMoreElements()) {
81: list.add(enumeration.nextElement());
82: }
83:
84: iterator = list.iterator();
85: } else {
86: List list = new ArrayList(1);
87: list.add(value);
88: iterator = list.iterator();
89: }
90:
91: return iterator;
92: }
93: }
|