|
|
@ -1,10 +1,14 @@ |
|
|
|
package com.my.graphiteDigesterBg.diframe.util; |
|
|
|
import java.io.File; |
|
|
|
import java.io.IOException; |
|
|
|
import java.net.JarURLConnection; |
|
|
|
import java.net.URL; |
|
|
|
import java.util.ArrayList; |
|
|
|
import java.util.Collections; |
|
|
|
import java.util.Enumeration; |
|
|
|
import java.util.List; |
|
|
|
import java.util.jar.JarEntry; |
|
|
|
|
|
|
|
public class DiClassHelper { |
|
|
|
// get all classes in package |
|
|
|
public static List<Class<?>> getAllClassesInPackage(String packageName) { |
|
|
@ -15,6 +19,8 @@ public class DiClassHelper { |
|
|
|
for (URL resource : resources) { |
|
|
|
if ( "file".equals(resource.getProtocol()) ) { |
|
|
|
DiClassHelper.getClassListByGivenFilePath(packageName,resource.getFile(), classes); |
|
|
|
} else if ( "jar".equals(resource.getProtocol()) ) { |
|
|
|
DiClassHelper.getClassListByGivenJarPath(packageName,resource, classes); |
|
|
|
} else { |
|
|
|
throw new RuntimeException("Unsupported protocol: " + resource.getProtocol()); |
|
|
|
} |
|
|
@ -25,6 +31,38 @@ public class DiClassHelper { |
|
|
|
return classes; |
|
|
|
} |
|
|
|
|
|
|
|
// get class list by given jar path |
|
|
|
private static void getClassListByGivenJarPath( String packageName, URL resource, List<Class<?>> classes ) { |
|
|
|
JarURLConnection urlConnection = null; |
|
|
|
try { |
|
|
|
urlConnection = (JarURLConnection) resource.openConnection(); |
|
|
|
} catch (IOException e) { |
|
|
|
throw new RuntimeException(e); |
|
|
|
} |
|
|
|
|
|
|
|
Enumeration<JarEntry> entries = null; |
|
|
|
try { |
|
|
|
entries = urlConnection.getJarFile().entries(); |
|
|
|
} catch (IOException e) { |
|
|
|
throw new RuntimeException(e); |
|
|
|
} |
|
|
|
|
|
|
|
while (entries.hasMoreElements()) { |
|
|
|
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 |
|
|
|
JarEntry entry = entries.nextElement(); |
|
|
|
String entryName = entry.getName(); |
|
|
|
if ( entryName.endsWith(".class") ) { |
|
|
|
try { |
|
|
|
String className = entryName.substring(0, entryName.length() - 6); |
|
|
|
className = className.replace("/", "."); |
|
|
|
classes.add(Class.forName(className)); |
|
|
|
} catch (ClassNotFoundException e) { |
|
|
|
throw new RuntimeException(e); |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
// get class list by given file path |
|
|
|
private static void getClassListByGivenFilePath( String packageName, String filePath, List<Class<?>> classes ) { |
|
|
|
File file = new File(filePath); |
|
|
|