Here's the snippet I used, ran with Maven and Eclipse IDE, target/test-classes is in the class-path.
String name = "aflexi.itest.properties" // System CL println ClassLoader.getSystemClassLoader() // Uses system or bootstrap CL println ClassLoader.getSystemResource(name) // Caller CL println ClassLoader.getCallerClassLoader() println ClassLoader.getCallerClassLoader().getResource(name) // Class's class loader. Perfectly fine in both places println getClass().getClassLoader() println getClass().getClassLoader().getResource("aflexi.itest.properties") // Doesn't work anywhere, the CL is the one of previous, but the name will be resolved as "net/aflexi/cdn/test/itest/aflexi.itest.properties" println getClass().getClassLoader0() println getClass().getResource("aflexi.itest.properties") // Doesn't work either. Using Groovy's calling class. println ReflectionUtils.getCallingClass() println ReflectionUtils.getCallingClass().getResource("aflexi.itest.properties")
And here's the result:
Expression / Class Loader | Test 1: Instance | Test 2: Instance | Test 1: Found Resource? | Test 2: Found Resource? |
---|---|---|---|---|
ClassLoader.getSystemClassLoader().getResource() | sun.misc.Launcher$AppClassLoader@19134f4 | sun.misc.Launcher$AppClassLoader@19134f4 | 1 | 0 |
ClassLoader.getCallerClassLoader().getResource() | sun.misc.Launcher$AppClassLoader@19134f4 | org.codehaus.groovy.tools.RootLoader@8965fb | 1 | 1 |
getClass().getClassLoader().getResource() | groovy.lang.GroovyClassLoader$InnerLoader@14177f3 | groovy.lang.GroovyClassLoader$InnerLoader@dc0435 | 1 | 1 |
getClass().getResource() | groovy.lang.GroovyClassLoader$InnerLoader@14177f3 | groovy.lang.GroovyClassLoader$InnerLoader@dc0435 | 0 | 0 |
ReflectionUtils.getCallingClass().getResource() | class cuke4duke.internal.groovy.GroovyLanguage | class groovy.ui.GroovyMain | 0 | 0 |
Take note that, getClass().getResource() uses the same CL instance (otherwise system CL) with getClass().getClassLoader().getResource(). The reason why it failed is that, it resolves the name of the properties file with package name, i.e. aflexi.itest.properties to net/aflexi/cdn/test/itest/aflexi.itest.properties.