Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast across classloader?

How can I do this:

class Foo {   public static Foo get() throws Exception {     ClassLoader cl = new URLClassLoader(new URL[]{"foo.jar"}, null); // Foo.class is in foo.jar     return (Foo)cl.loadClass("Foo").newInstance(); // fails on class cast   } } 

What I need is for the JVM to consider the Foo instance from cl as if it is an instance of Foo from the classloader of the executing code.

I have seen these approaches, none of them good for me (the above example is a toy example):

  1. Load the class (or a separate interface) by a class loader that is a parent of both the calling code and created classloader
  2. Serialize and deserialize the object.
like image 805
IttayD Avatar asked Apr 07 '10 10:04

IttayD


People also ask

What is meant by ClassLoader?

The Java Class Loader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Usually classes are only loaded on demand. The Java run time system does not need to know about files and file systems as this is delegated to the class loader.

What are different types of ClassLoader?

As we can see, there are three different class loaders here: application, extension, and bootstrap (displayed as null). The application class loader loads the class where the example method is contained. An application or system class loader loads our own files in the classpath.

Can we load the same class by two ClassLoader?

So when a class is loaded into JVM, you have an entry as (package, classname, classloader). Therefore the same class can be loaded twice by two different ClassLoader instances.

When would you use a ClassLoader?

Java uses ClassLoader implicitly when you use new , import keyword, the jvm will use the current class's classloader to load the dependent classes, so you can use the custom classloader to load a bootstrap class explicitly by using classloader.


1 Answers

Not possible. Class identity consists of the fully qualified name and the class loader.

Casting an object to a class with the same name loaded by different classloaders is no different than trying to cast a String to Integer, because those classes really could be completely different despite having the same name.

like image 163
Michael Borgwardt Avatar answered Sep 28 '22 10:09

Michael Borgwardt