01: // Copyright (c) Finn Bock
02:
03: package org.python.core;
04:
05: import java.lang.reflect.Method;
06: import java.util.Collection;
07: import java.util.Iterator;
08: import java.util.Map;
09:
10: class CollectionIter2 extends CollectionIter {
11: CollectionIter2() throws Exception {
12: Class.forName("java.util.Collection");
13: }
14:
15: PyObject findCollection(Object object) {
16: if (object instanceof Map) {
17: return new IteratorIter(((Map) object).keySet().iterator());
18: }
19: if (object instanceof Collection) {
20: return new IteratorIter(((Collection) object).iterator());
21: }
22: if (object instanceof Iterator) {
23: return new IteratorIter(((Iterator) object));
24: }
25: try {
26: // TODO - Once we depend on Java 5 we can replace this with a check
27: // for the Iterable interface
28: Method m = object.getClass().getMethod("iterator",
29: new Class[0]);
30: if (Iterator.class.isAssignableFrom(m.getReturnType())) {
31: return new IteratorIter((Iterator) m.invoke(object,
32: new Object[0]));
33: }
34: } catch (Exception e) {
35: // Looks like one of the many reflection based exceptions ocurred so
36: // we won't get an Iterator this way
37: }
38: return null;
39: }
40: }
41:
42: class IteratorIter extends CollectionIter {
43: private Iterator proxy;
44:
45: public IteratorIter(Iterator proxy) {
46: this .proxy = proxy;
47: }
48:
49: public PyObject __iternext__() {
50: if (!this.proxy.hasNext())
51: return null;
52: return Py.java2py(this.proxy.next());
53: }
54: }
|