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):
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With