gpt4 book ai didi

java - 类加载器 : how to load class from another project

转载 作者:搜寻专家 更新时间:2023-11-01 02:50:35 24 4
gpt4 key购买 nike

我想使用 ClassLoader 从另一个项目访问一个类。如何指定该类的路径并获取该类文件?

我希望能够通过代码完成此操作,因为我将通过我的应用程序加载许多不同的类文件,并且不同类的路径将不断变化。

我正在使用 CustomClassLoader,它正在加载类文件,但前提是它们在项目中而不是在另一个项目中

import java.io.FileInputStream;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;

public class CustomClassLoader extends ClassLoader {

String repoLocation = "C:/TempBINfolder/bin/";

public CustomClassLoader() {
}

public CustomClassLoader(ClassLoader parent) {
super(parent);
}

@Override
protected Class<?> findClass(final String name)
throws ClassNotFoundException {

AccessControlContext acc = AccessController.getContext();

try {
return (Class) AccessController.doPrivileged(
new PrivilegedExceptionAction() {

public Object run() throws ClassNotFoundException {

FileInputStream fi = null;
try {

String path = name.replace('.', '/');
fi = new FileInputStream(repoLocation + path
+ ".class");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[8192]; // a big chunk
int read;
while ((read = fi.read(buffer)) > 0)
baos.write(buffer, 0, read);
byte[] classBytes= baos.toByteArray();

return defineClass(name, classBytes, 0,
classBytes.length);
} catch (Exception e) {
throw new ClassNotFoundException(name);
}
}
}, acc);
} catch (java.security.PrivilegedActionException pae) {
return super.findClass(name);
}
}
}

调用类

for (Class singleClass : listOfClasses) {
try {

ClassLoader classLoader = new CustomClassLoader(ClassLoader.getSystemClassLoader());
Class stringClass = null;
try {
stringClass = classLoader.loadClass(singleClass.getName());
} catch (ClassNotFoundException ex) {
Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex);
}
try {
stringClass.newInstance();
} catch (InstantiationException ex) {
Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex);
}


Class cls = Class.forName(stringClass.getName());

如果我尝试执行 Class cls = Class.forName(stringClass.getPackage()+"."+stringClass.getName()); 包为 null

编辑:以下对我有用

URL classUrl;
classUrl = new URL("file:///"+ccl.getRepoLocation()); //This is location of .class file
URL[] classUrls = {classUrl};
URLClassLoader ucl = new URLClassLoader(classUrls);
Class cls = ucl.loadClass(stringClass.getName()); // Current .class files name

最佳答案

使用 URLClassLoader为你做到这一点。

关于java - 类加载器 : how to load class from another project,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12035782/

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