有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java自定义类加载器:有些类不是由我的类加载器加载的

我正在编写一个自定义类加载器,通过使用参数将其设置为默认类加载器

-Djava.system.class.loader=MyClassLoader

大多数类都是由我的类加载器加载的,但有些类不是,为什么? 这些类被保存到一个外部jar文件中

更新 这里有一个例子

public class Main{
    public static void main(String[] args) {
        try{
            // A simple class loader, ovveride loadClass
            // method and print in stdout the name of the class loaded.
            MyClassLoader classLoader=new MyClassLoader(MyClassLoader.class.getClassLoader());
            Class init=classLoader.loadClass("Initializer");
            Object instance=init.newInstance();
            init.getMethod("init").invoke(instance);
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

public class A{

    public A() {
        System.out.println("Im A");
    }
}

public class Initializer {

     public void init() {
        A a=new A();
    }
}

问题是:我希望类A由我的类装入器装入,但这并没有发生,为什么

更新

无论如何,我想用我的类加载器加载我的所有类,因为我想加密类代码并在运行时解密它。 那么,如何使用我的类加载器作为所有类的默认类加载器呢

谢谢


共 (1) 个答案

  1. # 1 楼答案

    java.lang下的任何内容都将始终由引导类加载器加载

    http://en.wikipedia.org/wiki/Java_Classloader

    When the JVM is started, three class loaders are used[3][4]:

    1. Bootstrap class loader
    2. Extensions class loader
    3. System class loader

    The bootstrap class loader loads the core Java libraries[5] (/lib directory). This class loader, which is part of the core JVM, is written in native code.

    The extensions class loader loads the code in the extensions directories (/lib/ext or any other directory specified by the java.ext.dirs system property). It is implemented by the sun.misc.Launcher$ExtClassLoader class.