Java 扫描指定包下面的类

思路重点

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
    .ideamisc.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]);
				}
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值