为什么 ClassLoader 在保存全局信息时从特定的 class 创建?

Why is ClassLoader created from specific class when holds global information?

我刚刚意识到这有时会 return null(在控制台中打印 null):

package myproject;
public class A {
   public static void main(String[] args) throws Exception
   {
     System.out.println(A.class.getClassLoader().getResource("A.class"));
   }
}

尽管 ClassLoader 是从 A.class 创建的,但它与它无关。它将从当前 运行ning 类路径加载资源。

我在 运行ning Maven 测试 类 时意识到了这一点 运行,默认情况下,在 project/target/test-classes 而正常的 类,就像A以上,在project/target/classes/.

我觉得这很令人困惑。我们为什么不得到类似 Class.getClassLoader 的东西来表明这是一个全球性的事情?还有,既然ClassLoader没用,那么开发者用什么来加载自己项目相关的资源呢?如果您包含 .jar 依赖项,它会起作用,包括资源。

首先:两个不同的 classes可以被不同的class加载器加载。所以,当你这样做时:

ClassLoader forA = A.class.getClassLoader();
ClassLoader forB = B.class.getClassLoader();

非常可能

if (forA.equals(forB)) {
  print equal
} else {
  print not equal
}

将打印 not equal!

因此,您使用单个 global Class.getClassLoader() 的想法立即失效:因为没有单个实体可以调用此方法 return .

对于另一部分 - 关于访问资源...看看 SO 问题。

每个 class 都与加载 class 的 class 加载程序关联。让 Class 有一个 getClassLoader 实例方法是完全合理的。

通过 get 方法拥有多个不同的对象 return 同一个对象没什么 "wrong"。

这就像拥有,说 person.getAddress()。一个家庭中的所有人可能 return 相同的地址,但这并不意味着拥有 static Person.getAddress.

是有意义的