-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClassUtils.java
More file actions
74 lines (67 loc) · 2.58 KB
/
ClassUtils.java
File metadata and controls
74 lines (67 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package DesignPattern.FactoryMethodPattern;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* @author [email protected]
* Created by zacky on 22:59.
*/
public class ClassUtils {
public static List<Class> getAllClassByInstance(Class c) {
List<Class> returnClassList = new ArrayList<>();
//接口不做任何处理
if (c.isInterface()) {
String packageName = c.getPackage().getName();//获取当前的包名
try {
List<Class> allClass = getClass(packageName);
//去重
for (int i = 0; i < allClass.size(); i++) {
if (c.isAssignableFrom(allClass.get(i))) {
if (!c.equals(allClass.get(i))) {
returnClassList.add(allClass.get(i));
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return returnClassList;
}
private static List<Class> getClass(String packageName) throws IOException, ClassNotFoundException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String path = packageName.replace(".", "/");
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList<Class> classes = new ArrayList<>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes;
}
private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
List<Class> 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;
}
}