01: package it.stefanochizzolini.reflex;
02:
03: import java.io.*;
04: import java.util.*;
05: import java.util.jar.*;
06: import java.net.*;
07:
08: public class Package {
09: /**
10: Retrieves all the statically-available local classes
11: belonging to the specified package.
12:
13: @param packageName The package name to search.
14: @return A list of the available classes within the specified package.
15: */
16: public static List<java.lang.Class> getClasses(String packageName) {
17: return getClasses(packageName, (System
18: .getProperty("sun.boot.class.path")
19: + File.pathSeparator // Bootstrap classes.
20: + System.getProperty("java.ext.dirs")
21: + File.pathSeparator // Extension classes.
22: + System.getProperty("java.class.path") // User classes.
23: ).split(File.pathSeparator));
24: }
25:
26: /**
27: Retrieves all the statically-available classes
28: belonging to the specified package
29: and located in any specified location.
30:
31: @param packageName The package name to search.
32: @param locations The local paths to search.
33: @return A list of the available classes within the specified package.
34: */
35: public static List<java.lang.Class> getClasses(String packageName,
36: String[] locations) {
37: try {
38: String packagePath = packageName.replace('.', '/') + '/';
39: String osDependentPackagePath = packagePath.replace('/',
40: File.separatorChar);
41: ArrayList<java.lang.Class> classes = new ArrayList<java.lang.Class>();
42: for (String location : locations) {
43: File locationFile = new File(location);
44: if (!locationFile.exists())
45: continue;
46:
47: if (locationFile.isDirectory()) // Directory.
48: {
49: locationFile = new File(location + File.separator
50: + osDependentPackagePath);
51: if (!locationFile.exists())
52: continue;
53:
54: // Get the list of the files contained in the package!
55: String[] filePaths = locationFile.list();
56: for (String filePath : filePaths) {
57: // Is it a class?
58: if (filePath.endsWith(".class")) {
59: classes
60: .add(java.lang.Class
61: .forName(packageName
62: + '.'
63: + filePath
64: .substring(
65: 0,
66: filePath
67: .length() - 6)));
68: }
69: }
70: } else // JAR file.
71: {
72: JarFile jarFile = new JarFile(locationFile);
73: for (Enumeration entries = jarFile.entries(); entries
74: .hasMoreElements();) {
75: String jarEntryPath = ((JarEntry) entries
76: .nextElement()).getName();
77: if (jarEntryPath.startsWith(packagePath)
78: && jarEntryPath.endsWith(".class")) {
79: classes.add(java.lang.Class
80: .forName(jarEntryPath.substring(0,
81: jarEntryPath.length() - 6)
82: .replaceAll("/", ".")));
83: }
84: }
85: }
86: }
87:
88: return classes;
89: } catch (Exception e) {
90: throw new RuntimeException(e);
91: }
92: }
93: }
|