解决方案是创建一个自定义
LoaderDelegate实现,该实现提供已加载类的实例,而不是再次加载它们。一个简单的示例是使用默认实现
DefaultLoaderDelegate(source)并覆盖
findClass其内部的方法
RemoteClassLoader
@Overrideprotected Class<?> findClass(String name) throws ClassNotFoundException { byte[] b = classObjects.get(name); if (b == null) { Class<?> c = null; try { c = Class.forName(name);//Use a custom way to load the class } catch(ClassNotFoundException e) { } if(c == null) { return super.findClass(name); } return c; } return super.defineClass(name, b, 0, b.length, (CodeSource) null);}要创建一个有效的JShell实例,请使用以下代码
JShell shell = JShell.builder() .executionEngine(new ExecutionControlProvider() { @Override public String name() { return "name"; } @Override public ExecutionControl generate(ExecutionEnv ee, Map<String, String> map) throws Throwable { return new DirectExecutionControl(new CustomLoaderDelegate()); } }, null) .build();shell.addToClasspath("Example.jar");//Add custom classes to Classpath, otherwise they can not be referenced in the JShell


