getClass().getResource() in static context
Asked Answered
B

2

8

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?

Brogue answered 7/5, 2014 at 16:7 Comment(5)
What error are you getting? Are you sure you have the image in the classpath?Crocket
ClassName.class is exactly the same as SomeClassReference.getClass(). You are getting the class of the StaticResource class.Devries
@Crocket it either outputs null or throws a NullPointerExceptionBrogue
Don't use in this way. Why are using getClassLoader()? Simply use StaticResource.class.getResource("image.png")Illegitimate
Always try to place the resources outside the JAVA code to make it more manageable and reusable by other package's class.Illegitimate
J
8

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

URL u = StaticResource.class.getResource("image.png");
Jamijamie answered 7/5, 2014 at 16:16 Comment(1)
+1 X.class.getClass() is always going to be the Class class as all Classes have a type of Class As this is loaded by the boot loader, it almost never has the resource you want. ;)Paget
I
0

Always try to place the resources outside the JAVA code to make it more manageable and reusable by other package's class.

You can try any one

// Read from same package 
URL url = StaticResource.class.getResource("c.png");

// Read from same package 
InputStream in = StaticResource.class.getResourceAsStream("c.png");

// Read from absolute path
File file = new File("E:/SOFTWARE/TrainPIS/res/drawable/c.png");

// Read from images folder parallel to src in your project
File file = new File("images/c.jpg");

// Read from src/images folder
URL url = StaticResource.class.getResource("/images/c.png")

// Read from src/images folder
InputStream in = StaticResource.class.getResourceAsStream("/images/c.png")
Illegitimate answered 7/5, 2014 at 16:11 Comment(3)
I don't get the last 3 - they seem to make assumptions on the structure of some project, which may (or rather may not) apply to someone else's setup.Fanniefannin
I want to try to keep resources outside the packages.Illegitimate
just create the images folder to place all the images inside this folder.Illegitimate

© 2022 - 2024 — McMap. All rights reserved.