I'm setti开发者_开发问答ng up a dev environment and I have this bit of code bothering me:
public static URI getResource(Class<?> cl, String resource) {
URL url = cl.getResource(resource);
//etc...
}
Problem is: url is null. The ressource in question is a file located in the exact directory as the java file. And this is supposed to return a non null url.
This environment has been installed sucessfully by many people, but it does not work on my machine.
Additional info:
- getRessource() is supposed to use the classLoader of cl. (This classLoader).toString() gives: "sun.misc.Launcher$AppClassLoader@11b86e7"
- This code is in a jUnit test which I run through eclipse Indigo on Windows 7 (problem of different file context in linux/windows?)
The classloader is expecting to get the resource file from the same directory as the .class file, not the .java file. Depending on how your Eclipse project is configured, these may be different directories.
Normally, your build process will copy the resource file to the output directory as it creates the .class files, but in this case, maybe it didn't?
The cl.getResource(resource)
call is attempting to locate the resource corresponding to the resource
String on the classpath of the classloader for cl
.
This means that resource
needs to be a path relative to your application's classpath.
The fact that the method call is returning null
means that the classloader can't find the requested resource. You need to check that the resource is being copied to the right place (by Eclipse or the builder) before the unit test is run.
(problem of different file context in linux/windows?)
It is possibly a resource name case-sensitivity issue. I doubt it if the tests run normally for other people, but it is worth checking.
Does this project have a build.xml
file? Try running the tests from the command line using Ant
.
Does this project have pom.xml
files? Try running the tests from the command line using mvn test
.
What is the class being passed? If it is a J2SE class, the class loader will be the bootstrap class-loader, and will not locate application resources.
Class.getResource(String)
will look for a resource inside the same package folder as the .class.
ClassLoader.getResource(String)
will look for a resource inside the src folder.
new File(String)
will look for a resource outside the src folder.
精彩评论