Search code examples
javaurlstaticgetresource

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?


Solution

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

    URL u = StaticResource.class.getResource("image.png");