4

我想使用 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
4

3 回答 3

2

使用URLClassLoader为您执行此操作。

于 2012-08-20T10:17:58.257 回答
2

该代码看起来不错(我自己很久以前做过类似的事情)。虽然有一个小错误:

如果你这样做

byte[] classBytes = new byte[fi.available()];
fi.read(classBytes);

您只读取与没有阻塞的可用字节一样多的字节。是的,您没有阅读整个文件。实际上,read 方法并不能保证会读取完整的字节缓冲区。

试着做:

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[] bytesClass = baos.toByteArray();

或使用Apache 的Streams.copy。这是一种方便的方法。

包定义

ClassLoader 有一个definePackage方法。我敢打赌,您应该为您需要的每个新包调用该方法。否则 ClassLoader 无法定义包,只能从完整的类名中定义,这似乎还不够。

所以代码得到这个:

// being package the name of the package for the new class
// being definedPackages a Set<String> member of the classloader

if (!this.definedPackages.contains(package)) {
   definePackage(package,"","","","","","",null);
   this.definedPackages.add(package);
}
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[] bytesClass = baos.toByteArray();
于 2012-08-20T10:19:53.880 回答
0

感谢上面帮助我的代码。

SUB : 在两个不同的位置调用相同的类

我在类路径 jar 文件中有一个类说 Abc,并且我在本地目录中动态生成了相同的类 Abc,并进行了一些代码更改。

我需要在本地目录中创建实例并使用类 Abc,下面是工作代码,

类 CustomClassLoader 扩展 ClassLoader {

String repoLocation = "./";
//C:/TempBINfolder/bin/
 CustomClassLoader() {
}

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

调用 CustomClassLoader 类,

    ClassLoader classLoader = new CustomClassLoader(ClassLoader.getSystemClassLoader());
    Class stringClass = (new CustomClassLoader(ClassLoader.getSystemClassLoader())).findClass(packageName+"."+javaFileName);
    Object  t = (Object) stringClass.newInstance();

谢谢, 默瓦特

于 2012-08-23T07:13:23.740 回答