gpt4 book ai didi

java - ContextClassLoader 没有 Hook

转载 作者:搜寻专家 更新时间:2023-10-31 19:58:41 25 4
gpt4 key购买 nike

我正在尝试定义自定义类加载器。

public class ExampleLoader extends ClassLoader
{
public Class<?> findClass(String name) throws ClassNotFoundException
{
System.out.println("This never gets printed");
return super.findClass(name);
}

public Class<?> loadClass(String name, boolean b)
throws ClassNotFoundException
{
System.out.println("This never gets printed");
return super.loadClass(name, b);
}
}

当然还有我的代码来测试它:

public class Tester
{
public static void main(String[] args)
{
Thread t = new FooThread();
t.setContextClassLoader(new ExampleLoader());
t.start();
}
}

class FooThread extends Thread
{
public void run()
{
new RandomClass();
}
}

问题是我的台词永远不会打印出来。显然我错过了一些东西。

最佳答案

这与 bug 4868493 有关.这是相关的引用:

Unfortunately the documentation for getContextClassLoader and setContextClassLoader might lead one to the conclusion that the submitter's code should work as expected.

However, there is a basic rule in class loading - no class can ever automatically load a class which is "downstream", i.e. which cannot be directly loaded by that class' ClassLoader or one of its ancestor ClassLoaders.

This is described in a number of places. For example, meditate on the white paper available here: http://www.javageeks.com/Papers/ClassForName/index.html to gain enlightenment.

The key point seems to be that the context class loader is not used automatically by the Java language. It's only a conventional place to store the context class loader so that other classes can use it with the 3-argument form of Class.forName.

The spec for Thread.getContextClassLoader and Thread.setContextClassLoader should be clarified, and the meaning of "context class loader" should be clarified. Re-classifying as a doc bug.

规范尚未明确。

要让它按您最初的要求运行,请将 new RandomClass() 替换为

Class.forName(RandomClass.class.getName(), 
true,
getContextClassLoader()).newInstance();

这会矛盾地打印出以下内容:

This never gets printed

关于java - ContextClassLoader 没有 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3432976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com