Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 507
u123 Avatar asked Sep 27 '10 11:09

u123


People also ask

What is getClassLoader in Java?

getClassLoader() is the same as the class loader for its element type; if the element type is a primitive type, then the array class has no class loader. Applications implement subclasses of ClassLoader in order to extend the manner in which the Java virtual machine dynamically loads classes.

What is getResource?

The getResource() method of java Class class is used to return the resources of the module in which this class exists. The value returned from this function exists in the form of the object of the URL class.

How to use getResource method in java?

Class getResource() method in Java with ExamplesThe method returns the specified resource of this class in the form of URL object. Parameter: This method accepts a parameter resourceName which is the resource to get. Return Value: This method returns the specified resource of this class in the form of URL objects.

Why use ClassLoader getResource?

2. The getResource() Method. We can use the getResource() method on either a Class or ClassLoader instance to find a resource with the given name. The resource is considered to be data — for instance, images, text, audio, and so on.


1 Answers

When you use

this.getClass().getResource("myFile.ext") 

getResource will try to find the resource relative to the package. If you use:

this.getClass().getResource("/myFile.ext") 

getResource will treat it as an absolute path and simply call the classloader like you would have if you'd done.

this.getClass().getClassLoader().getResource("myFile.ext") 

The reason you can't use a leading / in the ClassLoader path is because all ClassLoader paths are absolute and so / is not a valid first character in the path.

like image 62
AmishDave Avatar answered Sep 17 '22 17:09

AmishDave