View Javadoc

1   package jp.liq.container.reflect;
2   
3   import java.io.BufferedReader;
4   import java.io.IOException;
5   import java.io.InputStreamReader;
6   import java.net.URL;
7   import java.util.Iterator;
8   
9   import jp.liq.container.reflect.ReflectException.Reason;
10  
11  
12  public class ClassListLoader implements Iterable<Class<?>> {
13      private final URL url;
14      private final BufferedReader reader;
15      private final ClassLoader loader;
16  
17      public ClassListLoader(URL url, ClassLoader loader) {
18          try {
19              this.url = url;
20              this.reader = new BufferedReader(new InputStreamReader(url.openStream()));
21              this.loader = loader;
22          } catch (IOException e) {
23              throw new ReflectException(e, Reason.FAILED_TO_OPEN_URL, url);
24          }
25      }
26  
27      public Iterator<Class<?>> iterator() {
28          return new LineClassIterator();
29      }
30  
31      private class LineClassIterator implements Iterator<Class<?>> {
32          private Class<?> next;
33          private int lineNum;
34  
35          LineClassIterator() {
36              readNext();
37          }
38          public boolean hasNext() {
39              return next != null;
40          }
41  
42          public Class<?> next() {
43              Class<?> rv = next;
44              readNext();
45              return rv;
46          }
47  
48          public void remove() {
49              throw new UnsupportedOperationException();
50          }
51  
52          private void readNext() {
53              String line = null;
54  
55                  while(true) {
56                      try {
57                          lineNum++;
58                          line = reader.readLine();
59                      } catch (IOException e) {
60                          throw new ReflectException(e, Reason.FAILED_TO_READ_CLASS, 
61                                  url, lineNum, line);
62                      }
63                      if(line == null) {
64                          next = null;
65                          break;
66                      } else if(line.startsWith("#")) {
67                          continue;
68                      } else {
69                          try {
70                              next = loader.loadClass(line.trim());
71                              break;
72                          } catch (ClassNotFoundException e) {
73                              throw new ReflectException(e, Reason.FAILED_TO_READ_CLASS,
74                                      url, lineNum, line);
75                          }
76                          
77                      }
78                  }
79          }
80      }
81  }