0

I've wasted to much time on this one. Why does this code fails to result the URL to the class?

package org.test;

import java.net.URL;

public class Testa {

    public Testa() {

        String resourceName =  "org/test/Testa.class";
        String clazz = "org.test.Testa";

        try {
            Class.forName(clazz);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        URL url = this.getClass().getResource(resourceName);

        System.out.println("Why is this null? >>> " + url);
    }

    public static void main(String[] args) {

        new Testa();
    }
}
Amin Abu-Taleb
  • 4,423
  • 6
  • 33
  • 50
perseger
  • 77
  • 2
  • 11
  • I guess you are using the Default class loader which was used initially to find the class and again you are using the same class loader for loading the class. Which will not be found. – Narendra Pathai Sep 04 '13 at 09:20
  • This solution works for me: https://stackoverflow.com/questions/4301329/java-class-getresource-returns-null/50387930#50387930 – Taras Melnyk May 17 '18 at 10:03

3 Answers3

0

The code only needs to provide the class name:

URL url = this.getClass().getResource("Testa.class");

From the Java Doc:

Given the binary name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

The resource's path is relative to the Class path.

package org.test;

import java.net.URL;

public class Testa {

    public Testa() {

        String resourceName =  "Testa.class"; // /org/test/Testa.class would be looking for /org/test/org/test/Testa.class
        String clazz = "org.test.Testa";

        URL url = this.getClass().getResource(resourceName);
    }

    public static void main(String[] args) {

        new Testa();
    }
}
Amin Abu-Taleb
  • 4,423
  • 6
  • 33
  • 50
0

It will work and will print the URL by one correction as below.

*. Prefix "/" to your resourceName String.

String resourceName =  "/org/test/Testa.class";

OR

*. String resourceName =  "Testa.class";//No need to mention full path - resources work with relative path

Reason is (From JavaDoc)

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'. Otherwise, the absolute name is of the following form: modified_package_name/name

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

Ashay Thorat
  • 643
  • 5
  • 12