java custom classloader: some classes are not loaded by my classloader

南楼画角 提交于 2019-12-11 12:18:42

问题


i'm writing a custom classloader, i'have set it to be the default classloader by using the parameter

-Djava.system.class.loader=MyClassLoader

Most of the classes are loaded by my classloader, but some classes not, why? This classes are into an external jar file.

UPDATE Here an example

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();
    }
}

The problem is: I expect that class A are loaded by my class loader, but this is does not happen, why?

UPDATE

Anyway, i want to load ALL my classes with my class loader, becouse i want to encrypt class code and decrypt it at runtime. So, how can i use my class loader as default class loader for ALL my classes?

Thanks.


回答1:


Anything under java.lang will always be loaded by the bootstrap classloader.

From 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.



来源:https://stackoverflow.com/questions/4776456/java-custom-classloader-some-classes-are-not-loaded-by-my-classloader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!