[eclipse] this.getClass().getClassLoader().getResource("...") and NullPointerException

I have created a minimal maven project with a single child module in eclipse helios.

In the src/test/resources folder I have put a single file "install.xml". In the folder src/test/java I have created a single package with a single class that does:

  @Test
  public void doit() throws Exception {
    URL url = this.getClass().getClassLoader().getResource("install.xml");
    System.out.println(url.getPath());

  }

but when I run the code as a junit 4 unit test I just get a NullPointerException. This has worked fine a million of times before. Any ideas?

I have followed this guide:

http://www.fuyun.org/2009/11/how-to-read-input-files-in-maven-junit/

but still get the same error.

This question is related to eclipse maven-2 classloader

The answer is


I think I did encounter the same issue as yours. I created a simple mvn project and used "mvn eclipse:eclipse" to setup a eclipse project.

For example, my source file "Router.java" locates in "java/main/org/jhoh/mvc". And Router.java wants to read file "routes" which locates in "java/main/org/jhoh/mvc/resources"

I run "Router.java" in eclipse, and eclipse's console got NullPointerExeption. I set pom.xml with this setting to make all *.class java bytecode files locate in build directory.

<build>
    <defaultGoal>package</defaultGoal>
    <directory>${basedir}/build</directory>
<build>

I went to directory "build/classes/org/jhoh/mvc/resources", and there is no "routes". Eclipse DID NOT copy "routes" to "build/classes/org/jhoh/mvc/resources"

I think you can copy your "install.xml" to your *.class bytecode directory, NOT in your source code directory.


I had the same issue working on a project with Maven. Here how I fixed it: I just put the sources (images, musics and other stuffs) in the resources directory:

src/main/resources

I created the same structure for the packages in the resources directory too. For example:

If my class is on

com.package1.main

In the resources directory I put one package with the same name

com.package1.main

So I use

getClass().getResource("resource.png");

It should be getResource("/install.xml");

The resource names are relative to where the getClass() class resides, e.g. if your test is org/example/foo/MyTest.class then getResource("install.xml") will look in org/example/foo/install.xml.

If your install.xml is in src/test/resources, it's in the root of the classpath, hence you need to prepend the resource name with /.

Also, if it works only sometimes, then it might be because Eclipse has cleaned the output directory (e.g. target/test-classes) and the resource is simply missing from the runtime classpath. Verify that using the Navigator view of Eclipse instead of the Package explorer. If the files is missing, run the mvn package goal.


One other thing to look at that solved it for me :

In an Eclipse / Maven project, I had Java classes in src/test/java in which I was using the this.getClass().getResource("someFile.ext"); pattern to look for resources in src/test/resources where the resource file was in the same package location in the resources source folder as the test class was in the the test source folder. It still failed to locate them.

Right click on the src/test/resources source folder, Build Path, then "configure inclusion / exclusion filters"; I added a new inclusion filter of **/*.ext to make sure my files weren't getting scrubbed; my tests now can find their resource files.


tul,

  • When you use .getClass().getResource(fileName) it considers the location of the fileName is the same location of the of the calling class.
  • When you use .getClass().getClassLoader().getResource(fileName) it considers the location of the fileName is the root - in other words bin folder.

Source :

package Sound;
public class ResourceTest {
    public static void main(String[] args) {
        String fileName = "Kalimba.mp3";
        System.out.println(fileName);
        System.out.println(new ResourceTest().getClass().getResource(fileName));
        System.out.println(new ResourceTest().getClass().getClassLoader().getResource(fileName));
    }
}

Output :

Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Sound/Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Kalimba.mp3

When eclipse runs the test case it will look for the file in target/classes not src/test/resources. When the resource is saved eclipse should copy it from src/test/resources to target/classes if it has changed but if for some reason this has not happened then you will get this error. Check that the file exists in target/classes to see if this is the problem.


I had the same issue with the following conditions:

  • The resource files are in the same package as the java source files, in the java source folder (src/test/java).
  • I build the project with maven on the command line and the build failed on the tests with the NullPointerException.
  • The command line build did not copy the resource files to the test-classes folder, which explained the build failure.
  • When going to eclipse after the command line build and rerun the tests in eclipse I also got the NullPointerException in eclipse.
  • When I cleaned the project (deleted the content of the target folder) and rebuild the project in Eclipse the test did run correctly. This explains why it runs when you start with a clean project.

I fixed this by placing the resource files in the resources folder in test: src/test/resources using the same package structure as the source class.

BTW I used getClass().getResource(...)


Examples related to eclipse

How do I get the command-line for an Eclipse run configuration? My eclipse won't open, i download the bundle pack it keeps saying error log strange error in my Animation Drawable How to uninstall Eclipse? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Class has been compiled by a more recent version of the Java Environment Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9 "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Examples related to maven-2

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project. Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved Maven Error: Could not find or load main class MAVEN_HOME, MVN_HOME or M2_HOME Where is my m2 folder on Mac OS X Mavericks Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec 'mvn' is not recognized as an internal or external command, operable program or batch file SLF4J: Class path contains multiple SLF4J bindings Create local maven repository

Examples related to classloader

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger How to get names of classes inside a jar file? How do I put all required JAR files in a library folder inside the final JAR file with Maven? Dealing with "Xerces hell" in Java/Maven? What is the difference between Class.getResource() and ClassLoader.getResource()? How to use ClassLoader.getResources() correctly? this.getClass().getClassLoader().getResource("...") and NullPointerException Load properties file in JAR? Difference between thread's context class loader and normal classloader URL to load resources from the classpath in Java