简体   繁体   中英

Java ClassLoader not caching the class

I am trying to force some of the classes to be loaded using my custom class loader, the problem is after the loading the calling class still doesn't know about the class definition and tries to load it again, of course after that we have two different definitions of the class and assigning one to the other results in class cast exception. Any pointers or ideas how this can be fixed?

This is the calling class:

 CustomClassLoader loader = new CustomClassLoader(this.getPackageCodePath());
 Class<?> midletClass = loader.loadClass(className);
 midletClass.getMethod("InitEngine", Class.forName("android.app.Activity")).invoke(null, this);
 ms_MIDlet = (MIDlet)midletClass.newInstance();//ClassCastException

And this is the class loader itself

public class CustomClassLoader extends PathClassLoader
{
    public CustomClassLoader(String path)
    {
         super(path, getSystemClassLoader());//we set the parent to be the system class loader so the loading gets done in this class
    }

    @Override
    public InputStream getResourceAsStream(String resName)
    {
        //...do some resource loading here
    }
}

The calling class is running in some ClassLoader A . This classloader knows where to find and load MIDlet.class . Otherwise line 4 would produce a ClassNotFoundException for the cast.

You also use an instance of CustomClassLoader to load the Midlet.class.

On line 4 this blows up because you are casting the Midlet instance loaded by CustomClassLoader to a Midlet instances loaded by the ClassLoader A .

One solution is to make the CustomClassLoader logic delegate to ClassLoader A before loading a class itself. Something along the lines of first delegating a loadClass call to parentLoader.loadClass or getResourceAsStream to parentLoader.getResourceAsStream. If those calls fail then you can do your custom resource lookup.

This approach will make sure that all Midlet.class'es are actually loaded by the same classloader. You can check the delegation example at Java ClassLoader delegation model?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM