Java 本机库已加载到另一个类加载器中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3724421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Native Library already loaded in another classloader
提问by Rishikesh
I need some help to handle following scenario.
我需要一些帮助来处理以下情况。
I am using two applets which requires the same native library (.dll) file.
我正在使用两个需要相同本机库 (.dll) 文件的小程序。
So when I run the applets from the web pages, for the first time first applet loads the dll into the applet class loader. It works fine.
But when second applet tries to load the same dll it gives me exception saying that "Error loading win32com: java.lang.UnsatisfiedLinkError: Native Library C:\WINDOWS\system32\win32com.dll already loaded in another classloader"
因此,当我从网页运行小程序时,第一次小程序将 dll 加载到小程序类加载器中。它工作正常。但是当第二个小程序尝试加载相同的 dll 时,它给了我一个异常说"Error loading win32com: java.lang.UnsatisfiedLinkError: Native Library C:\WINDOWS\system32\win32com.dll already loaded in another classloader"
I using following method to load the driver.
我使用以下方法加载驱动程序。
CommDriver driver = (CommDriver)Class.forName("com.sun.comm.Win32Driver").newInstance();
driver.initialize();
Please give me the solution
请给我解决方案
Thanks & Rgds, Rishikesh
谢谢 & Rgds,瑞诗凯诗
回答by Joe
In short, the sameinstanceof the class that uses the native library must be shared by both classes.
简而言之,使用本机库的类的同一个实例必须由两个类共享。
You can do this by getting the system class loader (or the top parent of the class loader of your current class) and then dynamically have it load the class which uses the native library.
您可以通过获取系统类加载器(或当前类的类加载器的顶级父级)然后动态加载使用本机库的类来实现此目的。
If you don't know which class does load the native library then you can make a proxy class and load this isntead. The class must call to the other libraries for you so they will be loaded with the Proxy classes classloader (and so also be shared).
如果您不知道哪个类确实加载了本机库,那么您可以创建一个代理类并加载它。该类必须为您调用其他库,以便它们将与代理类类加载器一起加载(并且也被共享)。
However I would expect the security manager to prevent you from doing this within an Applet.
但是,我希望安全管理器阻止您在 Applet 中执行此操作。
回答by Kishor Prakash
There is no point in loading the Native Library(as a matter of fact any library)twice in different locations.
You can make Applet1's*driver* object as static.
And use it in Applet2.
在不同位置两次加载本机库(实际上是任何库)是没有意义的。您可以将Applet1 的* driver* 对象设为static。
并在Applet2 中使用它。