如何加载不在类路径中的类

在某些情况下,您可能需要加载一些不在类路径中的类。

Java示例

假设文件夹“ c:\\ other_classes \\ ”不在您的项目类路径中,这是一个示例,说明如何从该文件夹加载Java类。 代码和注释是不言自明的。

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.ProtectionDomain;

public class App{

	public static void main(String[] args) {
		
	try{
	
		File file = new File("c:\\other_classes\\"); 

                //convert the file to URL format
		URL url = file.toURI().toURL(); 
		URL[] urls = new URL[]{url}; 
			
                //load this folder into Class loader
		ClassLoader cl = new URLClassLoader(urls); 

                //load the Address class in 'c:\\other_classes\\'
		Class  cls = cl.loadClass("com.mkyong.io.Address");		
		
                //print the location from where this class was loaded
		ProtectionDomain pDomain = cls.getProtectionDomain(); 
		CodeSource cSource = pDomain.getCodeSource(); 
		URL urlfrom = cSource.getLocation();
		System.out.println(urlfrom.getFile());
	
	}catch(Exception ex){
		ex.printStackTrace();
	}
  }
}

输出量

/c:/other_classes/

您会注意到该类是从“ / c:/ other_classes / ”加载的,该类不在您的项目类路径中。

翻译自: https://mkyong.com/java/how-to-load-classes-which-are-not-in-your-classpath/

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值