Java ClassLoader change

前端 未结 3 678
生来不讨喜
生来不讨喜 2020-12-19 07:36

I have some class A:

public class A {
    public A(String str) {
        System.out.println(\"Create A instance: \" + str);
    }

    public vo         


        
相关标签:
3条回答
  • 2020-12-19 08:14

    As Marko Topolnik points out the context classloader is for use by frameworks. To use the classloader yourself you have to call loadClass("somepackage.A") and then use the reflection API to create a new instance of A (Class.newInstance()).

    You wont be able to use A or its methods in your source directly since the calling code does not know A - it uses a different classloader. An interface or baseclass of A that can be loaded by the normal classloader can be used to avoid reflection.

    interface AIF{
            void someMethod();
     }
    class A implements AIF{
          public void someMethod(){}
     }
    
    
    public void test(){
         MyLoader loader = new MyLoader();
         Class cla = loader.loadClass("A");
         AIF a = (AIF) cla.newInstance();
         a.someMethod();
    
     }
    
    0 讨论(0)
  • 2020-12-19 08:21

    The contextClassLoader mechanisms is not used by the basic Java operations like new. It's only there so various frameworks can access the context class loader in charge and load resources, classes, etc. Java will always use the classloader that loaded the code that is executing. It's the one that you access via ChangeLoaderTest.class.getClassLoader() -- and there is nothing you can do about this one.

    0 讨论(0)
  • 2020-12-19 08:23

    I think that what happens is that your application's class loader which is also your classloader's "parent" can locate A and load it. As a result your classloader will not be searched or used for loading A.

    To be honest, I haven't much experience with classloaders but if you subclassed one that uses a URL for the path of the class (so that it can locate the class file) and the parent classloader can not load it (not part of classpath), your custom one will be used.

    0 讨论(0)
提交回复
热议问题