IntelliJ项目中Scala如何获取被调用模块otherModule的资源路径?
获取otherModule自身路径的解决方案
当其他模块调用otherModule的方法时,直接用getClass.getResource("/")会因为类加载器上下文的问题返回调用模块的路径,要获取otherModule自身的路径,可以用以下几种可靠方式:
方式一:使用模块内类的类加载器
在otherModule的任意类中,通过该类的类加载器来获取资源根路径,确保使用的是模块自身的类加载器:
// 假设当前类是otherModule中的OtherModuleService URL moduleRootUrl = OtherModuleService.class.getClassLoader().getResource(""); if (moduleRootUrl != null) { String moduleRootPath = moduleRootUrl.getPath(); // 这里拿到的就是otherModule的资源根路径 }
方式二:基于Java模块系统(JPMS)直接获取模块位置
如果项目使用了Java模块系统(module-info.java),可以直接获取模块的位置信息:
// 同样使用otherModule内的类 Module currentModule = OtherModuleService.class.getModule(); Optional<URI> moduleLocation = currentModule.getLayer() .configuration() .findModule(currentModule.getName()) .flatMap(ModuleReference::location); if (moduleLocation.isPresent()) { String modulePath = moduleLocation.get().getPath(); // 处理模块路径 }
方式三:通过模块内标记资源定位
在otherModule的resources目录下创建一个空的标记文件(比如module_identity.marker),然后通过这个文件的位置反推模块根路径:
URL markerUrl = OtherModuleService.class.getResource("/module_identity.marker"); if (markerUrl != null) { String markerFullPath = markerUrl.getPath(); // 截取掉标记文件的文件名部分,得到模块根路径 String moduleRootPath = markerFullPath.substring(0, markerFullPath.lastIndexOf("/module_identity.marker")); }
核心原理
getClass.getResource("/")默认使用调用方的上下文类加载器,所以会指向调用模块的资源路径。而上面的方法都是强制使用otherModule自身类关联的类加载器或模块信息,确保资源查找的上下文是otherModule本身。
内容的提问来源于stack exchange,提问作者user13800089
相关产品推荐
相关产品推荐

