最近要写一个获取所有实现了Runnable接口的类,然而写完后发现项目没打包成可运行jar包时可以正常运行,一旦打包后就无法运行了。经过资料搜索,自己实现了一个。代码如下:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import lombok.extern.log4j.Log4j;
@SuppressWarnings("unchecked")
@Log4j
public class ClassUtils {
public static List<Class> getAllImplClassesByInterface(Class c,
String packageName) {
List<Class> returnClassList = new ArrayList<Class>();
if (c.isInterface()) {// 判断是否是接口
try {
List<Class> allClass = getClassesByPackageName(packageName);// 根据jar包中某一目录获取该目录下所有类
for (int i = 0; i < allClass.size(); i++) {
if (c.isAssignableFrom(allClass.get(i))) {// (自身类.class).isAssignableFrom(自身类或子类.class)
if (!c.equals(allClass.get(i))) {
returnClassList.add(allClass.get(i));
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnClassList;
}
private static List<Class> getClassesByPackageName(String packageName)
throws IOException, ClassNotFoundException {
File file = new File(System.getProperty("user.dir"));
String path = file.getAbsolutePath();// 当前目录下绝对路径
JarFile jarFile = new JarFile(path + "/MySpider_News.jar");// 要获取的jar包
Enumeration<JarEntry> entrys = jarFile.entries();
List<Class> classes = new ArrayList<Class>();
while (entrys.hasMoreElements()) {
JarEntry jarEntry = entrys.nextElement();
if (jarEntry.getName().endsWith(".class")) {
if (jarEntry.getName().contains("$"))
continue;
String className = jarEntry.getName().substring(0,
jarEntry.getName().length() - 6).replaceAll("/", ".");
if (className.contains(packageName))
classes.add(Class.forName(className));
}
}
return classes;
}
}