我知道这个问题之前已经被问过:
如何使用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);
}
URL.toURI().toURL()
的意义是什么? - Andreas_sUserHashClassName
是什么。同样,我们也不知道_sHashFunctionFilePath
是什么。 - Andreas