1 | package net.sourceforge.retroweaver.runtime.java.lang; |
2 | |
3 | import java.lang.reflect.Method; |
4 | import java.util.Collection; |
5 | import java.util.Iterator; |
6 | |
7 | /** |
8 | * Replacements for methods added to java.lang.Iterable in Java 1.5, used |
9 | * for targets of the "foreach" statement. |
10 | */ |
11 | public final class Iterable_ { |
12 | |
13 | private Iterable_() { |
14 | // private constructor |
15 | } |
16 | |
17 | /** |
18 | * Returns an iterator for <code>iterable</code>. |
19 | * |
20 | * @param iterable the object to get the Iterator from |
21 | * @return an Iterator. |
22 | * @throws UnsupportedOperationException if an iterator method can not be found. |
23 | * @throws NullPointerException if <code>iterable</code> is null. |
24 | */ |
25 | public static Iterator iterator(final Object iterable) { |
26 | if (iterable == null) { |
27 | throw new NullPointerException(); // NOPMD by xlv |
28 | } |
29 | |
30 | if (iterable instanceof Collection) { |
31 | // core jdk classes implementing Iterable: they are not weaved but, |
32 | // at least in 1.5, they all implement Collection and as its iterator |
33 | // method exits in pre 1.5 jdks, a valid Iterator can be returned. |
34 | return ((Collection) iterable).iterator(); |
35 | } |
36 | |
37 | if (iterable instanceof net.sourceforge.retroweaver.runtime.java.lang.Iterable) { |
38 | // weaved classes inheriting from Iterable |
39 | return ((net.sourceforge.retroweaver.runtime.java.lang.Iterable) iterable).iterator(); |
40 | } |
41 | |
42 | // for future jdk Iterable classes not inheriting from Collection |
43 | // use reflection to try to get the iterator if it was present pre 1.5 |
44 | try { |
45 | final Method method = iterable.getClass().getMethod("iterator", (Class[]) null); |
46 | if (method != null) { |
47 | return (Iterator) method.invoke(iterable, (Object[]) null); |
48 | } |
49 | } catch (Exception ignored) { // NOPMD by xlv |
50 | } |
51 | |
52 | throw new UnsupportedOperationException("iterator call on " + iterable.getClass()); |
53 | } |
54 | |
55 | } |