0

note: this is a named-module java project

Why does getting a resources in java work like this? I got two packages, in main func both are printing the URL of "/respath/tmp.txt" in a jar-file syntax with corresponding to its classes.

How does this code really deffer to each other?

// mod-one
package com.pkg.one;
import ...
import com.pkg.two.ClassNameTwo;
class ClassNameOne {
    ... main()
        print(ClassNameOne.class.getResource("/resPath/tmp.txt")); // works fine
        print(ClassNameTwo.getCustomRes("resPath/tmp.txt", ClassNameOne.class); // it return null
}

note: this is a named-module java project

// mod-two
package com.pkg.two;
import ...
class ClassNameTwo {

    /**
     return "ClassLoader.getSystemResource(...)" if sourceClass is null.
     */
    public static URL getCustomRes(String sourcePath, Class<?> sourceClass) {
        ...
        URL url = null;
        if (sourceClass == null)
            url = ClassLoader.getSystemResource(sourcePath);
        else
            url = sourceClass.getResource("/" + sourcePath);    
        ...
        return url;
        }
}

1 Answers1

0

ok, I got an answer.Because this is a named-module java project you need to give access at to your "resouce-dir" to another module but why did it gives me a warning: "package is empty or does not exist", when it is not empty?

e.q:

module mod.one { // this module need to access the "res-dir" of mod.two
   requires mod.two;
   ...
}

module mod.two {
   ...
   opens my.path.to.res; // dir: my/path/to/res
}

And can we access/modify a third-party module res-dir that is not open?

  • "_but why did it gives me a warning: "package is empty or does not exist", when it is not empty?_" – Are you using Maven or Gradle? If so, then the reason might be because technically the resources aren't in the module (at compile-time) due to the separation of `src/main/java` and `src/main/resources`. This is not really a problem, as everything ends up together when packaged. – Slaw Nov 11 '21 at 05:10
  • Also, note what you're dealing with is known as "encapsulation". It's described here: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Module.html#getResourceAsStream(java.lang.String) – Slaw Nov 11 '21 at 05:14
  • Oh thank you very much for the info. yes I'm using a build-tool, is there a way to stop/fix the warning? – Liveon Phoenix Nov 11 '21 at 05:24
  • Which build tool are you using? – Slaw Nov 11 '21 at 05:29
  • @Slaw, um its Gradle build tool. – Liveon Phoenix Nov 11 '21 at 05:37
  • One of my answers to a different question provides some workarounds when using Gradle: https://stackoverflow.com/questions/51864473/where-do-resource-files-go-in-a-gradle-project-that-builds-a-java-9-module/51921521#51921521. But I do stand by what I said before in my now-deleted comment: Fixing this may be more effort than it's worth, especially if everything is working. – Slaw Nov 11 '21 at 05:41