思路重点
String f = Thread.currentThread()
.getContextClassLoader()
.getResource(packName.replace(“.”, “/”))
.getFile();
重点是上面那行代码,它是获取编译后根目录的地址。
- 比如在
eclipse
中
它获取到的地址其实就是bin
的地址,查看项目下面的.classpath
就知道它指向的是bin
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="lib" path="E:/eclipse/jar/mybatis-3.5.4.jar"/>
<classpathentry kind="lib" path="E:/eclipse/jar/mysql-connector-java-8.0.30.jar"/>
<classpathentry kind="lib" path="E:/eclipse/jar/fastjson2-2.0.19.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
- 在
idea
中
在.idea
的misc.xml
中就可以找到编译文件输出到out下面,所以上面那行代码就是拿到out这个文件夹的路径。
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="11" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
代码
class Main{
// 扫描指定包下的类
public Map<String, Method> scanPack(String packName) throws ClassNotFoundException {
Map<String, Method> hashMap = new HashMap<>();
String f = Thread.currentThread()
.getContextClassLoader()
.getResource(packName.replace(".", "/"))
.getFile();
// 队列
Deque<File> folder = new ArrayDeque<>();
folder.offer(new File(f));
while (!folder.isEmpty()) {
File file = folder.poll();
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; ++i) {
if (files[i].isDirectory()) folder.offer(files[i]);
else handlerClass(files[i], packName, hashMap);
}
} else {
handlerClass(file, packName, hashMap);
}
}
return hashMap;
}
// 获取到文件,加载class。
private void handlerClass(File file, String packName, Map<String, Method> hashMap) throws ClassNotFoundException {
String name = packName + "." + file.getName().replace(".class", "");
Class<?> clazz = Class.forName(name);
if (clazz != null) {
Method[] methods = clazz.getMethods();
for (int i = 0; i < methods.length; ++i) {
if (methods[i].isAnnotationPresent(com.org.util.Set.class)) {
methods[i].setAccessible(true);
hashMap.put(name + "." + methods[i].getName(), methods[i]);
}
}
}
}
}