Dynamic Class Loading in Java

来源:互联网 发布:软件怎么发布 编辑:程序博客网 时间:2024/05/02 02:49

It is possible to load and reload classes at runtime in Java, though it is not as straightforward as one might have hoped. This text will explain when and how you can load and reload classes in Java.

The ClassLoader

All classes in a Java application are loaded using some subclass ofjava.lang.ClassLoader. Loading classes dynamically must therefore also be done using a java.lang.ClassLoader subclass.

When a class is loaded, all classes it references are loaded too. This class loading pattern happens recursively, until all classes needed are loaded. This may not be all classes in the application. Unreferenced classes are not loaded until the time they are referenced.

Class Loading

The steps a given class loader uses when loading classes are:

  1. Check if the class was already loaded.
  2. If not loaded, ask parent class loader to load the class.
  3. If parent class loader cannot load class, attempt to load it in this class loader.

When you implement a class loader that is capable of reloading classes you will need to deviate a bit from this sequence. The classes to reload should not be requested loaded by the parent class loader.

Dynamic Class Loading

Loading a class dynamically is easy. All you need to do is to obtain a ClassLoaderand call its loadClass() method

原创粉丝点击