gpt4 book ai didi

java - 使用 Java 反射从类路径外加载类

转载 作者:搜寻专家 更新时间:2023-11-01 01:38:12 26 4
gpt4 key购买 nike

我想从不在类路径中的类加载类。有什么方法可以通过文件路径加载类而不是在类路径中?例如

ClassLoader.load("c:\MyClass.class");

最佳答案

示例取自 here :

// Create a File object on the root of the directory containing the class file  
File file = new File("c:\\myclasses\\");

try {
// Convert File to a URL
URL url = file.toURL(); // file:/c:/myclasses/
URL[] urls = new URL[]{url};

// Create a new class loader with the directory
ClassLoader cl = new URLClassLoader(urls);

// Load in the class; MyClass.class should be located in
// the directory file:/c:/myclasses/com/mycompany
Class cls = cl.loadClass("com.mycompany.MyClass");
} catch (MalformedURLException e) {
} catch (ClassNotFoundException e) {
}

关于java - 使用 Java 反射从类路径外加载类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5926144/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com