我正在尝试使用自定义类加载器而不是默认类加载器来加载无驱动程序AI执行(Java API)所需的类。 出于以下原因,需要自定义类加载器-
在使用自定义类加载器时,发现mojo2-runtime-api.jar中的MojoPipelineFactoryService.java使用ServiceLoader加载MojoPipelineFactory.class,而MojoPipelineFactory.class则将使用线程上下文类加载器。这将尝试从线程上下文类加载器而不是我的自定义类加载器加载类。
有什么办法可以解决这个问题?
这是我尝试执行的示例代码片段:
try{
File file = new File("mojo2-runtime-api-2.1.3.jar");
File file1 = new File("protobuf-java-3.7.1.jar");
File file2 = new File("mojo2-runtime-impl-2.1.3.jar");
File file3 = new File("joda-time-2.9.5.jar");
List<URL> urlsToLoad = new ArrayList<>();
urlsToLoad.add(file.toURI().toURL());
urlsToLoad.add(file1.toURI().toURL());
urlsToLoad.add(file2.toURI().toURL());
urlsToLoad.add(file3.toURI().toURL());
CustomClassLoader customLoader = new CustomClassLoader(urlsToLoad);
Thread.currentThread().setContextClassLoader(customLoader);
Class loadedClass = customLoader.loadClass("ai.h2o.mojos.runtime.MojoPipeline");
System.out.println("Loaded class : "+loadedClass.getName());
Method method = loadedClass.getMethod("loadFrom",String.class);
String fileName = "pipeline.mojo";
method.invoke(loadedClass, (Object) fileName);
} catch(Exception e){
e.printStackTrace();
}