Java resource from class vs Thread

前端 未结 2 761
天命终不由人
天命终不由人 2021-01-12 11:38

what is the difference between

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

vs

Thread.currentThread().getContextCla         


        
2条回答
  •  温柔的废话
    2021-01-12 12:11

    There is a special case getting the first class running (which is why you have to declare the main() method as static with an array of strings as an argument). Once that class is loaded and is running, future attempts at loading classes are done by the class loader. At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name. Each class in Java uses own classloader to load other classes. So if ClassA.class references ClassB.class then ClassB needs to be on the classpath of the ClassLoader of ClassA, or its parents.

    The thread context ClassLoader is a special one in that it is the current ClassLoader for the currently running thread. This is useful in multi-classloader environments. An object can be created from a class in ClassLoader C and then passed to a thread owned by ClassLoader D. In this case the object needs to use Thread.currentThread().getContextClassLoader() directly if it wants to load resources that are not available on its own ClassLoader .

提交回复
热议问题