【问题标题】:Class & ClassLoader类和类加载器
【发布时间】:2014-03-04 16:52:57
【问题描述】:

我有一个自定义类加载器:CustomClassLoader(extends ClassLoader)

我有一门课:IntegerPrint

我用我的自定义类加载器加载我的类。我期待下面代码中的 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());
    }
}

【问题讨论】:

    标签: java classloader


    【解决方案1】:

    你期待什么? 在

    System.out.println(IntegerPrinter.class.getClassLoader());
    

    你创建一个

     Class<IntegerPrint> 
    

    对象,当然,它的类 (Class) 一定是由某个类加载器加载的。没有天才可以想象Class 一定很早就被加载了,甚至在你的代码获得控制权之前。

    请运行您的示例

    java  -verbose:class ....
    

    查看哪些类按什么顺序加载。

    【讨论】:

      【解决方案2】:

      第一次通话:

      IntegerPrinter.class.getClassLoader()
      

      实际上会这样做:

      IntegerPrinterTest.class.getClassLoader().loadClass("IntegerPrinter")
      

      所以它完全忽略了您的自定义类加载器。 换句话说:您自己的类加载器实际上并未用于您使用“new”等本机调用创建的任何对象。为此,它还应该负责加载 IntegerPrinter 类。

      在同一个班级中这样做是相当谨慎的(而且通常是无用的),但你可以这样做:

      Class<?> clazz = loader.loadClass("IntegerPrinterTest");
      clazz.getMethod("main").invoke(null);
      

      (请注意,此代码未经测试,但应该近似于可行的东西)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-21
        • 1970-01-01
        相关资源
        最近更新 更多