Reprinted from Concurrent Programming network –ifeve.com
Content index
Class Loader
Class loading System
Class loading
Dynamic class Loading
Dynamic class overloading
Custom class Overloading
Class Loading/Overloading example
Java allows you to dynamically load and reload classes at run time, but this functionality is not as straightforward as people want. This article will explain how to load and overload classes in Java.
You may wonder why the Java Dynamic class loading feature is part of the Java reflection mechanism and not part of the Java core platform. Anyway, this article was put in the Java Reflection series and there was no better series to contain it.
Class Loader
Classes in all Java applications are loaded by a series of subclasses of the Java.lang.ClassLoader class. So if you want to load classes dynamically, you must also use Java.lang.ClassLoader subclasses.
Once a class is loaded, all classes referenced by this class are also loaded. The class loading process is a recursive pattern, and all related classes are loaded. But not necessarily all classes in an application will be loaded, and classes unrelated to the referenced chain of the loaded class will not be loaded until they are loaded when there is a referential relationship.
Class loading System
Class loading is an orderly system in Java. When you create a new standard Java ClassLoader, you must provide its parent loader. When a class loader is called to load a class, it first calls the loader's parent loader to load. If the parent loader cannot find the class, then the loader will attempt to load the class.
Class loading
The class loader loads the classes in the following order:
1. Check if this class has been loaded.
2. If not loaded, the parent loader is called first to load.
3. If the parent loader cannot load the class, try loading the class.
When you implement a ClassLoader with overloaded class functionality, the order is somewhat different from the above. The class overload is not requested by his parent loader to load. This will be explained in the following paragraphs.
Dynamic class Loading
Dynamic loading of a class is straightforward. All you have to do is get a class loader and then call its LoadClass () method. Here's an example:
Public class MainClass { publicstaticvoid main (string[] args) { = MainClass . class . getClassLoader (); Try { = Classloader.loadclass ("Com.jenkov.MyClass"); System.out.println ("aclass.getname () =" + aclass.getname ()); Catch (ClassNotFoundException e) { e.printstacktrace (); }}
Dynamic class overloading
Dynamic class overloading is a bit more complex. The Java built-in ClassLoader checks to see if it has already been loaded before loading a class. So overloading a class is not possible with the Java built-in ClassLoader, and if you want to overload a class you need to manually inherit the ClassLoader.
After you have customized ClassLoader subclasses, you still have some things to do. All loaded classes need to be linked. This process is done through the Classloader.resolve () method. Since this is a final method, this method cannot be overridden in ClassLoader subclasses. The Resolve () method does not allow a given ClassLoader instance to link a class two times. So whenever you want to reload a class you need to use a new ClassLoader subclass. This is a necessary condition when you are designing class overloading functions.
Custom class Overloading
As I said earlier, you cannot overload a class with a class loader that has already loaded the class. So you need other ClassLoader instances to overload this class. But this has brought some new challenges.
All classes that are loaded into the Java application are given the full name of the class (package name + class name) as a unique identifier for the ClassLoader instance to load. This means that the class MyObject is loaded by class loader A, and if class loader B loads the MyObject class, then the classes loaded by the two loaders are different. Take a look at the following code:
MyObject object = (MyObject) myclassreloadingfactory.newinstance ("Com.jenkov.MyObject");
The MyObject class is referenced in the above code, and its variable name is object. This causes the MyObject class to be loaded by the classloader of the class where the code resides.
If the Myclassreloadingfactory factory object uses a different class loader to overload the MyObject class, you cannot convert an instance of the overloaded MyObject class to an object variable of type MyObject. Once the MyObject class is loaded by two classloader, it is considered to be two different classes, although the full name of their class is exactly the same. If you try to convert instances of these two classes, you will report classcastexception.
You can fix this limitation, but you need to modify your code from the following two areas:
1. Mark this variable type as an interface, and then overload only the implementation class for this interface.
2. Mark this variable type as a superclass, and then overload only the subclass of the superclass class.
Take a look at these two examples:
Myobjectinterface object = (myobjectinterface) myclassreloadingfactory.newinstance ("Com.jenkov.MyObject") ;
//------------------------------------------------------------
Myobjectsuperclass object = (myobjectsuperclass) myclassreloadingfactory.newinstance ("Com.jenkov.MyObject");
As long as the type of the guaranteed variable is a superclass or an interface, these two methods can run normally, and when their subclasses or implementation classes are overloaded, the superclass and interfaces are not overloaded.
To ensure that this can be done you need to implement the ClassLoader manually and then make these interfaces or superclass loaded by its parent loader. When your ClassLoader loads the MyObject class, the superclass Myobjectsuperclass or interface Myobjectsuperclass will also be loaded because they are myobject dependent. Your classloader must proxy these classes to the same classloader, which loads the class that includes the interface or superclass.
Class Loading/Overloading example
Light says do not practice false bashi. Let's take a look at a simple example. The following example is a subclass of a class loader. Notice how this class does not want to be overloaded, and how it puts the load on a class into its parent loader. If a class is loaded by its parent loader, this class will not be overloaded later. Remember that a class can only be loaded once by the same ClassLoader instance.
As I said before, this is just a simple example that shows you the basic behavior of the ClassLoader. This is not a template that you can use directly to design your project's ClassLoader. The class loader you design yourself should be more than just one, and you might design a lot of loaders if you want to overload classes. And you won't be hard-coded (Hardcore) The path of the class you want to load into your code like this.
Public classMyclassloaderextendsclassloader{ PublicMyclassloader (ClassLoader parent) {Super(parent); } PublicClass loadclass (String name)throwsClassNotFoundException {if(!" Reflection. MyObject ". Equals (name))return Super. LoadClass (name); Try{String URL= "file:c:/data/projects/tutorials/web/web-inf/" + "Classes/reflection/myobject.class"; URL Myurl=Newurl (URL); URLConnection Connection=myurl.openconnection (); InputStream input=Connection.getinputstream (); Bytearrayoutputstream Buffer=NewBytearrayoutputstream (); intdata =Input.read (); while(Data! =-1) {buffer.write (data); Data=Input.read (); } input.close (); byte[] Classdata =Buffer.tobytearray (); returnDefineClass ("Reflection. MyObject ", Classdata,0, classdata.length); } Catch(malformedurlexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } return NULL; }}
Here's an example of using Myclassloader:
Public Static voidMain (string[] args)throwsclassnotfoundexception, Illegalaccessexception, instantiationexception {ClassLoader Parentclassloader
= Myclassloader.class. getClassLoader (); Myclassloader ClassLoader=NewMyclassloader (Parentclassloader); Class Myobjectclass= Classloader.loadclass ("Reflection. MyObject "); AnInterface2 Object1=(ANINTERFACE2) myobjectclass.newinstance (); Myobjectsuperclass Object2=(Myobjectsuperclass) myobjectclass.newinstance (); //Create new class loader so classes can is reloaded.ClassLoader =NewMyclassloader (Parentclassloader); Myobjectclass= Classloader.loadclass ("Reflection. MyObject "); Object1=(ANINTERFACE2) myobjectclass.newinstance (); Object2=(Myobjectsuperclass) myobjectclass.newinstance ();}
The following is the loaded reflection. MyObject class. Note that it inherits a superclass and also implements an interface. This is done only to demonstrate this feature through examples. You may only implement a class or inherit one or two interfaces in your custom case.
View Source code Printing Help
Public class extends Implements aninterface2{ //... the body of class ... override superclass methods // or Implement interface methods}
Original address Author: Jakob Jenkov Translator: Yevenhai ([email protected])
Java Reflection (12): Dynamic class loading and overloading