来自类与线程的Java资源 [英] Java resource from class vs Thread

查看:75
本文介绍了来自类与线程的Java资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

vs

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

我在src/test/resources&中有资源我正在尝试从单元测试访问它们.这是典型的maven样式目录结构.

I have resources in src/test/resources & I am trying to access them from Unit test. It's a typical maven style directory structure.

我期望两者表现相同.但是事实并非如此.getClass().getResource()无法获取资源,而从Thread可以获取资源.

I was expecting both to behave identical. But it's not., getClass().getResource() doesn't fetch the resource where as from Thread I am able to fetch the resource.

那么它们有何不同?

推荐答案

在特殊情况下,第一个类正在运行(这就是为什么您必须将main()方法声明为静态的,并将字符串数组作为参数的原因) ). 加载并运行该类后,类加载器将在以后尝试加载类.最简单的是,类加载器创建由字符串名称引用的类主体的平面名称空间. Java中的每个类都使用自己的类加载器来加载其他类.因此,如果ClassA.class引用ClassB.class,则ClassB必须位于ClassAClassLoader或其父级的类路径上.

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.

线程上下文ClassLoader是一个特殊的上下文,它是当前正在运行的线程的当前ClassLoader.这在多类加载器环境中很有用.可以从ClassLoader C中的类创建对象,然后将其传递给ClassLoader D拥有的线程.在这种情况下,如果对象要加载自身ClassLoader上不可用的资源,则需要直接使用Thread.currentThread().getContextClassLoader().

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 .

这篇关于来自类与线程的Java资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆