I just came to realise that this will sometimes return null (print null in console):
package myproject;
public class A {
public static void main(String[] args) throws Exception
{
System.out.println(A.class.getClassLoader().getResource("A.class"));
}
}
Even though the ClassLoader is created from A.class it has nothing to do with it. It will load resources from the currently running classpath.
I realised this when I was running Maven test classes which run, by default, in project/target/test-classes while the normal classes, like A above, are in project/target/classes/.
I think this is very confusing. Why don't we get something like Class.getClassLoader to make it obvious that this is a global thing? Also, since ClassLoader is useless, what do developers use to load resources relative to their projects? If you include .jar dependency it works, resources included.