java搜索类文件并且创建类spring
package com.cgx.logtest1; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.util.ResourceUtils; public class BuildCla { private Logger log = LoggerFactory.getLogger(getClass()); private static final String PACKET_CLASS = "com/cgx/logtest1/*.class"; private static final String CLASS_PREFIX = "com.cgx.logtest1."; private static final String CLASS_SUFFIX = ".class"; public List<Object> searchAndBuild() { log.info("开始查找类文件..."); long start = System.currentTimeMillis(); // 获取当前线程上下文类加载器 ClassLoader appClassLoader = Thread.currentThread() .getContextClassLoader(); List<Object> registerClasses = new ArrayList<>(); int total = 0; Resource[] resources = new Resource[0]; try { // 找到包路径下的所有类文件 resources = new PathMatchingResourcePatternResolver().getResources( ResourceUtils.CLASSPATH_URL_PREFIX + PACKET_CLASS); if (resources.length == 0) { log.info("{}路径的文件不存在!!!", PACKET_CLASS); return Collections.unmodifiableList(registerClasses); } // 通过类名创建类 for (Resource re : resources) { String fileName = re.getFilename(); if (fileName == null) continue; int classIndex = fileName.indexOf(CLASS_SUFFIX); fileName = fileName.substring(0, classIndex); String className = CLASS_PREFIX + fileName; // 类加载器创建类 Class<?> cla = appClassLoader.loadClass(className); // 打开访问权限,实例化 Constructor<?> constr = cla.getConstructor(); constr.setAccessible(true); registerClasses.add(cla.getConstructor().newInstance()); total++; } } catch (Exception e) { log.error(e.getMessage()); } long end = System.currentTimeMillis(); log.info("成功查找类文件{}个,创建类{}个, 耗时{}ms", resources.length, total, (end - start) / 1000); return Collections.unmodifiableList(registerClasses); } }
package com.cgx.logtest1; import java.util.List;public class Logtest1Application { public static void main(String[] args) { BuildCla cla = new BuildCla(); List<Object> cs = cla.searchAndBuild(); for (Object obj : cs) { System.out.println(obj.toString()); } } }