java 用于反射的Java方法(包扫描)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 用于反射的Java方法(包扫描)相关的知识,希望对你有一定的参考价值。
/**
* Scans all classes accessible from the context class loader which belong
* to the given package and subpackages.
*
* @param packageName The base package
* @return The classes
* @throws ClassNotFoundException
* @throws IOException
* @see https://dzone.com/articles/get-all-classes-within-package
*/
private static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
String path = packageName.replace('.', '/');
Enumeration resources = classLoader.getResources(path);
List dirs = new ArrayList();
while (resources.hasMoreElements()) {
URL resource = (URL) resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList classes = new ArrayList();
for (Object directory : dirs) {
classes.addAll(findClasses((File) directory, packageName));
}
return (Class[]) classes.toArray(new Class[classes.size()]);
}
/**
* Recursive method used to find all classes in a given directory and
* subdirs.
*
* @param directory The base directory
* @param packageName The package name for classes found inside the base
* directory
* @return The classes
* @throws ClassNotFoundException
* @see https://dzone.com/articles/get-all-classes-within-package
*/
private static List findClasses(File directory, String packageName) throws ClassNotFoundException {
List classes = new ArrayList();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
}
}
return classes;
}
/**
* Gets a class/classes in a package that are of a given type.
* org.reflections is required
*/
public Set getClassesInPackage(String pack, Class aClass) {
Reflections ref = new Reflections(pack, new SubTypesScanner(false));
// ? extends Fruit is example
Set<Class<? extends Fruit>> allClasses = ref.getSubTypesOf(aClass);
return allClasses;
}
/**
* Gets inherited (all) fields of a given type.
*
* @see http://stackoverflow.com/a/2405757/1766166
*/
public static List<Field> getInheritedFields(Class<?> type) {
List<Field> fields = new ArrayList<Field>();
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
fields.addAll(Arrays.asList(c.getDeclaredFields()));
}
return fields;
}
以上是关于java 用于反射的Java方法(包扫描)的主要内容,如果未能解决你的问题,请参考以下文章