JAva中パケットのスキャン
2876 ワード
JAva中パケットのスキャン
自分のパッケージとjarのパッケージを含む
自分のパッケージとjarのパッケージを含む
public abstract class PackageScanner {
public abstract void dealClass(Class> klass);
private boolean isClass(Class> klass) {
if (klass.isAnnotation()
|| klass.isInterface()
|| klass.isEnum()
|| klass.isPrimitive()) {
return false;
}
return true;
}
//
private void scanPackage(String packageName, File currentFile) {
//
File[] fileList = currentFile.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
}
return pathname.getName().endsWith(".class");
}
});
for (File file : fileList) {
if (file.isDirectory()) {
scanPackage(packageName + "." + file.getName(), file);
} else {
String fileName = file.getName().replace(".class", "");
String className = packageName + "." + fileName;
try {
//
Class> klass = Class.forName(className);
// ,
if (!isClass(klass)) {
continue;
}
//
dealClass(klass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
//jar
private void scanPackage(URL url) throws IOException {
JarURLConnection urlConnection = (JarURLConnection) url.openConnection();
JarFile jarFile = urlConnection.getJarFile();
Enumeration jarEntries = jarFile.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
String jarEntryName = jarEntry.getName();
//
if (jarEntry.isDirectory() || !jarEntryName.endsWith(".class")) {
continue;
} else {
try {
String klassName = jarEntryName.replace(".class", "").replace("/", ".");
//
Class> klass = Class.forName(klassName);
// ,
if(!isClass(klass)) {
continue;
}
//
dealClass(klass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
public void packageScan(String packageName) {
String packageOppositePath = packageName.replace(".", "/");
ClassLoader classLoder = Thread.currentThread().getContextClassLoader();
Enumeration resource;
try {
resource = classLoder.getResources(packageOppositePath);
//
while (resource.hasMoreElements()) {
URL url = resource.nextElement();
// jar
if (url.getProtocol().equals("jar")) {
scanPackage(url);
} else {
File file = new File(url.toURI());
if (!file.exists()) {
continue;
}
scanPackage(packageName, file);
}
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}