我有一个自定义类装入器:CustomClassLoader(扩展ClassLoader)
我有一门课: IntegerPrint
我用自定义ClassLoader加载我的类。我原以为下面代码中的SOP会返回相同的值。但是第一个SOP打印"sun.misc.Launcher$AppClassLoader@..“&第二个SOP打印”CustomClassLoader@.“
为什么会这样?请给我建议。
public class IntegerPrinterTest {
public static void main(String[] args) throws Exception {
CustomClassLoader loader = new CustomClassLoader(IntegerPrinterTest.class.getClassLoader());
Class<?> clazz = loader.loadClass("IntegerPrinter");
System.out.println(IntegerPrinter.class.getClassLoader());
System.out.println(clazz.getClassLoader());
}
}发布于 2014-03-04 08:32:48
你还想要什么?在……里面
System.out.println(IntegerPrinter.class.getClassLoader());您创建了一个
Class<IntegerPrint> 对象,当然,它的类(Class)肯定是由某个类加载器加载的。不难想象,Class一定是很早就加载的,甚至在代码获得控制之前也是如此。
请用
java -verbose:class ....查看哪些类是按什么顺序排列的。
发布于 2014-03-04 08:28:58
第一个电话:
IntegerPrinter.class.getClassLoader()将实际做到:
IntegerPrinterTest.class.getClassLoader().loadClass("IntegerPrinter")因此它完全忽略了您的自定义类加载器。换句话说:您自己的类加载器实际上并不用于使用本机调用(如"new“等)创建的任何对象。要做到这一点,它还应该负责加载IntegerPrinter类。
在同一个类中这样做是相当谨慎的(通常是无用的),但您可以这样做:
Class<?> clazz = loader.loadClass("IntegerPrinterTest");
clazz.getMethod("main").invoke(null);(请注意,这段代码没有经过测试,但应该近似于工作的内容)
https://stackoverflow.com/questions/22165920
复制相似问题