• 类加载器ClassLoader


    在项目中有时为了实现热部署,需要动态加载指定路径下的.class文件

    一般很少使用自定义的类加载器,而是用URLClassLoader去加载指定路径下的.class文件

    URLClassLoader 默认是去加载jar包下的.class文件

    public static void main(String[] args) throws ClassNotFoundException, IOException {
    	URL url=new URL("file:"+"E:"+File.separator+"workspace");
    	System.out.println(url.getPath());
    	String path=url.getPath();
    	File file = new File(path);
    	getfiles(file);
    }
    private static List<Class<?>> getfiles(File file) throws ClassNotFoundException, IOException {
    	List<Class<?>> classList=new ArrayList<>();
    	if(!file.exists())
    	{
    		return classList;
    	}
    	File[] files=file.listFiles();
    	for(File f:files){
    		if(f.isDirectory()){
    			List<Class<?>> subClasses=getfiles(file);
    			classList.addAll(subClasses);
    		}
    		else if (f.getName().endsWith(".jar")) {
    			URL url=new URL("file:"+f.getAbsolutePath());
    			System.out.println(url.getPath());
    			ClassLoader classLoader=new URLClassLoader(new URL[]{url});
    			JarFile jarFile=new JarFile(f);
    			Enumeration<JarEntry> jarEntries=jarFile.entries();
    			while(jarEntries.hasMoreElements()){
    				JarEntry jarEntry=jarEntries.nextElement();
    				if(jarEntry.getName().endsWith(".class")){
    					Class<?> clazz=classLoader.loadClass(jarEntry.getName().substring(0, jarEntry.getName().length()-6).replace("/", "."));
    					classList.add(clazz);
    					System.out.println(clazz.getName());
    				}
    			}
    		}
    	}
    	return classList;
    	
    }
    

      上述代码仅针对特定文件结构可以根据实际情况完善

    下面记录一下代码中存在的坑:
    ① 当用本地文件路径生成URL时,必须在前面加上“file:”

    ② 新建的URLClassLoader在默认情况下是指的jar包的URL,而f.getAbsolutePath()也只能获得本地的文件路径,需要在前面加上“file:”

    ③ jarEntry.getName() 获取的名字是***/***/*** 的格式,所以需要将“/”替换为“.” ,即packageName.className 格式。

  • 相关阅读:
    oracle单行函数 之 转换函数
    oracle单行函数 之 时间函数
    oracle单行函数 之 数字函数
    oracle单行函数 之 字符函数
    oracle 之 如何链接别人电脑的oracle
    轻应用介绍
    Web 目录枚举与遍历漏洞解决
    接口测试工具(Postman)
    Tomcat 编码不一致导致乱码
    持久化配置管理 diamond 使用简介
  • 原文地址:https://www.cnblogs.com/-cqq/p/10152848.html
Copyright © 2020-2023  润新知