Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getClass().getResource() in static context

I'm trying to get a resource (image.png, in the same package as this code) from a static method using this code:

import java.net.*;

public class StaticResource {

    public static void main(String[] args) {
        URL u = StaticResource.class.getClass().getResource("image.png");
        System.out.println(u);
    }

}

The output is just 'null'

I've also tried StaticResource.class.getClass().getClassLoader().getResource("image.png"); , it throws a NullPointerException

I've seen other solutions where this works, what am I doing wrong?

like image 291
Luke Moll Avatar asked May 07 '14 16:05

Luke Moll


People also ask

What is the getResource() method of class class in Java?

Class class getResource () method: Here, we are going to learn about the getResource () method of Class class with its syntax and example. getResource () method is available in java.lang package. getResource () method is used to return the URL (Uniform Resource Locator) with the given resource name.

How to call getresourceasstream in a static method?

Tags:java| properties file| resources To call getResourceAsStreamin a static method, we use ClassName.classinstead of getClass() 1. In non static method getClass().getClassLoader().getResourceAsStream("config.properties")) 2. In static method ClassName.class.class.getClassLoader().getResourceAsStream("config.properties")) 1. Non Static Method

What is the return value of getresourceasstream () method?

Return Value: This method returns the specified resource of this class in the form of InputStream objects. Exception This method throws: Below programs demonstrate the getResourceAsStream () method.

How to get the specified resource of a class in Java?

The getResource () method of java.lang.Class class is used to get the resource with the specified resource of this class. The 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.


1 Answers

Remove the ".getClass()" part. Just use

URL u = StaticResource.class.getResource("image.png");
like image 77
Ignacio A. Poletti Avatar answered Oct 12 '22 22:10

Ignacio A. Poletti