JAVA ClassLoader.class and any other explicite class calling of "getResource(...)" work differently?

72 Views Asked by At

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

There are 1 best solutions below

8
Liveon Phoenix On

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?