为什么 use-context-classloader 默认设置为true?
为什么Clojure不使用当前的类加载器?
答案 0 :(得分:4)
您可以通过将clojure.lang.Compiler.LOADER
设置为类加载器来覆盖其行为
即
final ClassLoader ccl= ClojurePlugin.class.getClassLoader();
clojure.lang.Var.pushThreadBindings(clojure.lang.RT.map( clojure.lang.Compiler.LOADER, ccl) );
try {
...
clojure.lang.RT.loadResourceScript( cljFile );
...
}finally{
clojure.lang.RT.popThreadBindings();
}
ClojurePlugin是你的班级。
但是当你第一次使用RT类时(即加载RT类时),它将使用上下文类加载器来加载ie。 clojure/core
,因此您可能希望将上述代码包装成:
ClassLoader previous = Thread.currentThread().getContextClassLoader();
final ClassLoader parentClassLoader = ClojurePlugin.class.getClassLoader();
Thread.currentThread().setContextClassLoader(parentClassLoader);
try {
...
//above code here
...
} finally {
Thread.currentThread().setContextClassLoader(previous);
}
否则您可能会收到一些错误消息,例如:
Caused by: java.io.FileNotFoundException: Could not locate clojure/core__init.class or clojure/core.clj on classpath:
at clojure.lang.RT.load(RT.java:432)
at clojure.lang.RT.load(RT.java:400)
at clojure.lang.RT.doInit(RT.java:436)
at clojure.lang.RT.<clinit>(RT.java:318)
... 16 more
否则如果你这样做而不是前者,你会得到类似的东西:
21:10:59 [SEVERE] java.io.FileNotFoundException: Could not locate Clojure resource on classpath: cljminecraft/core.clj
21:10:59 [SEVERE] at clojure.lang.RT.loadResourceScript(RT.java:366)
21:10:59 [SEVERE] at clojure.lang.RT.loadResourceScript(RT.java:346)
21:10:59 [SEVERE] at clojure.lang.RT.loadResourceScript(RT.java:338)
21:10:59 [SEVERE] at cljminecraft.ClojurePlugin.loadClojureFile(ClojurePlugin.java:25)
21:10:59 [SEVERE] at cljminecraft.ClojurePlugin.loadClojureNameSpace(ClojurePlugin.java:38)
21:10:59 [SEVERE] at cljminecraft.ClojurePlugin.start(ClojurePlugin.java:53)
21:10:59 [SEVERE] at cljminecraft.BasePlugin.onEnable(BasePlugin.java:235)
21:10:59 [SEVERE] at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:217)
21:10:59 [SEVERE] at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:374)
21:10:59 [SEVERE] at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:381)
21:10:59 [SEVERE] at org.bukkit.craftbukkit.CraftServer.loadPlugin(CraftServer.java:270)
21:10:59 [SEVERE] at org.bukkit.craftbukkit.CraftServer.enablePlugins(CraftServer.java:252)
21:10:59 [SEVERE] at net.minecraft.server.MinecraftServer.j(MinecraftServer.java:320)
21:10:59 [SEVERE] at net.minecraft.server.MinecraftServer.e(MinecraftServer.java:299)
21:10:59 [SEVERE] at net.minecraft.server.MinecraftServer.a(MinecraftServer.java:258)
21:10:59 [SEVERE] at net.minecraft.server.DedicatedServer.init(DedicatedServer.java:147)
21:10:59 [SEVERE] at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:398)
21:10:59 [SEVERE] at net.minecraft.server.ThreadServerApplication.run(SourceFile:856)
如果你不这样做(但你仍然会调用类似clojure.lang.RT.loadResourceScript( cljFile );
的内容,那么你会得到第一个错误(很明显)