java 9:关于资源和模块的混乱规则

时间:2018-03-01 15:06:24

标签: resources java-9

在com.thing.withprops模块中,我在com.thing.withprops.UseProps.java中有这段代码:

 URL url =UseProps.class.getResource("config/values.properties") ;

module-info是

module com.thing.withprops { exports com.thing.withprops;}

现在有另一个名为com.thing.withprops.config的模块,其中包含目录com / thing / withprops / config /中的values.properties文件 module-info就是这样:

module com.thing.withprops.config{}

当一切都被激怒并且执行完毕时,所有工作都完美无缺:资源被找到了!我很困惑,因为似乎医生说它不应该被找到,因为它是在另一个未导出或打开的模块中。 那有什么不对?我理解doc的方式(我不是母语人士)或我的代码?

感谢任何提示

1 个答案:

答案 0 :(得分:0)

实际上有两个问题:一个是关于处理资源而另一个是关于java -jar行为

这里有关于如何处理模块化项目中的资源的建议:

public interface ResourceLoader {
public static Optional<URL> resourceSearch(Class clazz, String name) {
    String fullPath = name ;
    if(! name.startsWith("/")) {
        String packageName = clazz.getPackageName();
        fullPath = '/'+packageName.replace('.','/')+ '/' + name;
    }

    ServiceLoader<ResourceLoader> loader = ServiceLoader.load(ResourceLoader.class);
    for(ResourceLoader resourceLoader: loader) {
        Optional<URL>  anUrl =resourceLoader.getResource(fullPath);
        if(anUrl.isPresent()) {
            return anUrl ;
        }
    }
    return Optional.empty() ;
}

public static Optional<InputStream>  resourceSearchAsStream(Class clazz, String name) throws IOException {
    Optional<URL> anURL = resourceSearch(clazz, name) ;
    if(anURL.isPresent()){
        InputStream is = anURL.get().openStream() ;
        return Optional.of(is) ;
    }
     return Optional.empty() ;
}

public default Optional<URL> getResource(String fullPath) {
    Class localClass = this.getClass() ;
    URL res = localClass.getResource(fullPath) ;
    return Optional.ofNullable(res) ;
}

}

然后可以使用模块信息部署另一个模块:

open module com.thing.withprops.config {
requires com.thing.withprops;
provides com.thing.withprops.utils.ResourceLoader with com.thing.withprops.spi.ResourceLoaderImpl ;

}

还有其他建议吗? (仍然试图找到一种方法,让某些东西看起来像一个&#34;可点击的&#34;罐子......但可能毫无希望)