"\u007b\n System.load("D:\syySdfHsm\msvcr110.dll");\n} "\n时发生 Native Library D:\syySdfHsm\msvcr110.dll already loaded in another classloader,\n\n为了避免发生 "Native Library already loaded in another classloader" 的错误,可以使用类似以下代码的优化方式:\n\njava\nimport java.io.File;\nimport java.lang.reflect.Field;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\n\npublic class NativeLibraryLoader {\n public static void load(String libraryPath) {\n try {\n File libraryFile = new File(libraryPath);\n Path tempLibraryPath = Files.createTempFile(\"temp\", libraryFile.getName());\n Files.copy(libraryFile.toPath(), tempLibraryPath, StandardCopyOption.REPLACE_EXISTING);\n \n System.load(tempLibraryPath.toString());\n \n // 清理临时文件\n Field field = ClassLoader.class.getDeclaredField(\"loadedLibraryNames\");\n field.setAccessible(true);\n Vector<String> loadedLibraryNames = (Vector<String>) field.get(null);\n loadedLibraryNames.remove(libraryFile.getName());\n \n // 将临时文件删除\n tempLibraryPath.toFile().deleteOnExit();\n } catch (Exception e) {\n e.printStackTrace();\n } \n }\n}\n\n\n然后在需要加载 native library 的地方,使用 NativeLibraryLoader.load(\"D:\\syySdfHsm\\msvcr110.dll\") 替代 System.load(\"D:\\syySdfHsm\\msvcr110.dll\")。\n\n这样做的原理是将原始的 native library 文件拷贝到一个临时文件中,然后通过 System.load 加载临时文件,再手动从 ClassLoaderloadedLibraryNames 中移除已加载的库,最后删除临时文件。\n\n这样可以确保每次加载库时都会重新加载,避免 "already loaded in another classloader" 的错误。


原文地址: https://www.cveoy.top/t/topic/qqJw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录