1. 程式人生 > 其它 >java搜尋類檔案並且建立類spring

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());
        }
    }

}