3

我知道以前有人问过这个问题:

如何使用 URLClassLoader 加载 *.class 文件?

但是,由于缺乏示例,我不太了解。我目前正在做一个项目并尝试加载用户给定的 .class 对象,这些对象可以位于机器上的任何目录中。

//Create URL to hash function class file
URL url_hashFunctionPath = new URL("file:///" + _sHashFunctionFilePath);

//Packet URL to a URL array to be used by URLClassLoader
URL[] urlA_hashFunctionPath = {url_hashFunctionPath};

//Load URL for hash function via a URL class loader
URLClassLoader urlCl_hashFunctionClassLoader = new URLClassLoader(urlA_hashFunctionPath);

//Load user hash function into class to initialize later (TEST: HARD CODE FOR NOW)
m_classUserHashClass = urlCl_hashFunctionClassLoader.loadClass(_sUserHashClassName);

最后一行给了我一个 ClassNotFoundException,从我的实验和理解用户给定的类函数必须在类路径中?

PS:第一次发布问题,请随时纠正我没有遵循适当方式的地方。

//解决方案

我在 [WillShackleford][1] 的慷慨帮助下得出的解决方案,该解决方案可以在给定的文件路径中加载 .class 文件。有关更多信息,请参阅代码及其给出的注释。

//The absolute file path to the class that is to be loaded (_sHashFunctionFilePath = absolute file path)
String pathToClassFile = _sHashFunctionFilePath;
System.out.println("File to class: " + _sHashFunctionFilePath);

//Declare the process builder to execute class file at run time (Provided filepath to class)
ProcessBuilder pb = new ProcessBuilder("javap", pathToClassFile);
try
{
    //Start the process builder
    Process p = pb.start();

    //Declare string to hold class name
    String classname = null;
    //Declare buffer reader to read the class file & get class name
    try(BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())))
    {
        String line;
        while(null != (line = br.readLine()))
        {
            if(line.startsWith("public class"))
            {
                classname = line.split(" ")[2];
                break;
            }
        }
        System.out.println("classname = " + classname);
    }
    catch(IOException _error)
    {

    }

    //Declare file path to directory containing class to be loaded
    String pathToPackageBase = pathToClassFile.substring(0, pathToClassFile.length() - (classname + ".class").length());
    System.out.println("pathToPackageBase = " + pathToPackageBase);

    try
    {
        //Create class to hold the class to be loaded via a URL class loader
        Class clss = new URLClassLoader(
                new URL[]{new File(pathToPackageBase).toURI().toURL()}
        ).loadClass(classname);

        //Create ab object/instance of said class
        Object test = clss.newInstance();

        //Declare & create requested method from user hash function class (Method is work & takes no arguments)
        Method method = clss.getMethod("work", null);
        method.invoke(test, null);
    }
4

2 回答 2

4

在目录/home/shackle/somedir/classes/pkg中,我有一个从 java 文件创建的文件 Test.class,package pkg;例如:

package pkg;

public class Test {

    public String toString() {
        return "secret_string";
    }
}

然后我加载它:

System.out.println(new URLClassLoader(
        new URL[]{new File("/home/shackle/somedir/classes").toURI().toURL()}
).loadClass("pkg.Test").newInstance().toString());

请注意,我没有将 pkg/Test 放在 URL 字符串中,但加载类参数具有 pkg​​。字首。

您可以像这样直接从文件中获取类名:

Class clsReaderClss = ClassLoader.getSystemClassLoader().loadClass("jdk.internal.org.objectweb.asm.ClassReader");
System.out.println("clsReaderClss = " + clsReaderClss);
Constructor con = clsReaderClss.getConstructor(InputStream.class);
Object reader = con.newInstance(new FileInputStream(directFile));
Method m = clsReaderClss.getMethod("getClassName");
String name = m.invoke(reader).toString().replace('/', '.');
System.out.println("name = " + name);

不需要访问内部类的替代方法。

String pathToClassFile = "/home/shackle/somedir/classes/pkg/Test.class";
ProcessBuilder pb = new ProcessBuilder("javap",pathToClassFile);
Process p = pb.start();
String classname = null;
try(BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
   String line;
   while(null != (line = br.readLine())) {
       if(line.startsWith("public class")) {
           classname = line.split(" ")[2];
           break;
       }
   }
}
System.out.println("classname = " + classname);

然后可以加载类:

String pathToPackageBase = pathToClassFile.substring(0, pathToClassFile.length() - (classname + ".class").length());
System.out.println("pathToPackagBase = " + pathToPackageBase);
Class clss = new URLClassLoader(
        new URL[]{new File(pathToPackageBase).toURI().toURL()}
).loadClass(classname);
System.out.println(clss.newInstance().toString());
于 2015-09-24T21:56:46.940 回答
0

_sHashFunctionFilePath需要从中删除目标类的包名,因此 ClassLoader 将在_sHashFunctionFilePath++中package.name查找HashFunction.class文件的路径。如果您不这样做,ClassLoader 将无法找到该文件。

因此,如果目标类my.great.HashFunction在 中,那么如果要使用 URLClassLoader HashFunction.class,它需要在一个名为的目录中。my/great/然后,/path/to如果file:///.class 文件实际上是在/path/to/my/great/HashFunction.class.

于 2015-09-24T21:59:06.607 回答