Java resource from vs Thread class

What's the difference between

getClass().getResource("some-resource-file.txt")

vs

Thread.currentThread().getContextClassLoader().getResource("some-resource-file.txt")

I have resources in src / test / resources and I'm trying to access them from Unit test. This is a typical maven style directory structure.

I expected both to be the same. But this is not so. GetClass (). GetResource () does not retrieve the resource, from where I can retrieve the resource from Thread.

So how are they different?

+4
source share
2 answers

, ( main() ). , . , . Java . , ClassA.class ClassB.class, ClassB ClassLoader ClassA .

ClassLoader , ClassLoader . . ClassLoader C, , ClassLoader D. Thread.currentThread().getContextClassLoader() , , ClassLoader.

+2

, , -.

, webapp, , .

Webapp , WEB-INF/classes WEB-INF/lib/*. jar . , , webapp, .

getClass().getResource(), , , . , , , , .

Thread.currentThread().getContextClassLoader() , , , , webapp, WEB-INF/classes WEB-INF/lib.

, . , (, ), -, , , -.

, , , ClassLoader . , ClassLoader , . , com.foo,

 MyClass.class.getResource("hello.txt")

MyClass.class.getResource("/com/foo/hello.txt")

MyClass.class.getClassLoader().getResource("com/foo/hello.txt");
+4

Source: https://habr.com/ru/post/1533480/


All Articles