技术经验分享:Java_动态加载类(英文)

简介: 技术经验分享:Java_动态加载类(英文)

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.


You can argue whether Java's dynamic class loading features are really part of Java Reflection, or a part of the core Java platform. Anyways, the article has been put in the Java Reflection trail in lack of a better place to put it.


The ClassLoader


All classes in a Java application are loaded using some subclass of //代码效果参考:http://www.jhylw.com.cn/133428655.html

java.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.


The ClassLoader Hierarchy


Class loaders in Java are organized into a hierarchy. When you create a new standard Java ClassLoaderyou must provide it with a parent ClassLoader. If a ClassLoader is asked to load a class, it will ask its parent class loader to load it. If the parent class loader can't find the class, the child class loader then tries to load it itself.


Class Loading


The steps a given class loader uses when loading classes are://代码效果参考:http://www.jhylw.com.cn/563439321.html


Check if the class was already loaded.


If not loaded, ask parent class loader to load the class.


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. More on that later.


Dynamic Class Loading


Loading a class dynamically is easy. All you need to do is to obtain a ClassLoader and call its loadClass()method. Here is an example:


public class MainClass {


public static void main(String【】 args){


ClassLoader classLoader = MainClass.class.getClassLoader();


try {


Class aClass = classLoader.loadClass("com.jenkov.MyClass");


System.out.println("aClass.getName() = " + aClass.getName());


} catch (ClassNotFoundException e) {


e.printStackTrace();


}


}


Dynamic Class Reloading


Dynamic class reloading is a bit more challenging. Java's builtin Class loaders always checks if a class is already loaded before loading it. Reloading the class is therefore not possible using Java's builtin class loaders. To reload a class you will have to implement your own ClassLoader subclass.


Even with a custom subclass of ClassLoader you have a challenge. Every loaded class needs to be linked. This is done using the ClassLoader.resolve() method. This method is final, and thus cannot be overridden in your ClassLoader subclass. The resolve() method will not allow any given ClassLoader instance to link the same class twice. Therefore, everytime you want to reload a class you must use a new instance of yourClassLoader subclass. This is not impossible, but necessary to know when designing for class reloading.


Designing your Code for Class Reloading


As stated earlier you cannot reload a class using a ClassLoader that has already loaded that class once. Therefore you will have to reload the class using a different ClassLoader instance. But this poses som new challenges.


Every class loaded in a Java application is identified by its fully qualified name (package name + class name), and the ClassLoader instance that loaded it. That means, that a class MyObject loaded by class loader A, is not the same class as the MyObject class loaded with class loader B. Look at this code:


MyObject object = (MyObject)


myClassReloadingFactory.newInstance("com.jenkov.MyObject");


Notice how the MyObject class is referenced in the code, as the type of the object variable. This causes theMyObject class to be loaded by the same class loader that loaded the class this code is residing in.


If the myClassReloadingFactory object factory reloads the MyObject class using a different class loader than the class the above code resides in, you cannot cast the instance of the reloaded MyObject class to the MyObjecttype of the object variable. Since the two MyObject classes were loaded with different class loaders, the are regarded as different classes, even if they have the same fully qualified class name. Trying to cast an object of the one class to a reference of the other will result in a ClassCastException.


It is possible to work around this limitation but you will have to change your code in either of two ways:


Use an interface as the variable type, and just reload the implementing class.


Use a superclass as the variable type, and just reload a subclass.


Here are two coresponding code examples:


MyObjectInterface object = (MyObjectInterface)


myClassReloadingFactory.newInstance("com.jenkov.MyObject");


MyObjectSuperclass object = (MyObjectSuperclass)


myClassReloadingFactory.newInstance("com.jenkov.MyObject");


Either of these two methods will work if the type of the variable, the interface or superclass, is not reloaded when the implementing class or subclass is reloaded.


To make this work you will of course need to implement your class loader to let the interface or superclass be loaded by its parent. When your class loader is asked to load the MyObject class, it will also be asked to load the MyObjectInterface class, or the MyObjectSuperclass class, since these are referenced from within theMyObject class. Your class loader must delegate the loading of those classes to the same class loader that loaded the class containing the interface or superclass typed variables.


ClassLoader Load / Reload Example


The text above has contained a lot of talk. Let's look at a simple example. Below is an example of a simpleClassLoader subclass. Notice how it delegates class loading to its parent except for the one class it is intended to be able to reload. If the loading of this class is delegated to the parent class loader, it cannot be reloaded later. Remember, a class can only be loaded once by the same ClassLoader instance.


As said earlier, this is just an example that serves to show you the basics of a ClassLoader's behaviour. It is not a production ready template for your own class loaders. Your own class loaders should probably not be limited to a single class, but a collection of classes that you know you will need to reload. In addition, you should probably not hardcode the class paths either.


public class MyClassLoader extends ClassLoader{


public MyClassLoader(ClassLoader parent) {


super(parent);


}


public Class loadClass(String name) throws ClassNotFoundException {


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 = new URL(url);


URLConnection connection = myUrl.openConnection();


InputStream input = connection.getInputStream();


ByteArrayOutputStream buffer = new ByteArrayOutputStream();


int data = input.read();


while(data != -1){


buffer.write(data);


data = input.read();


}


input.close();


byte【】 classData = buffer.toByteArray();


return defineClass("reflection.MyObject",


classData, 0, classData.length);


} catch (MalformedURLException e) {


e.printStackTrace();


} catch (IOException e) {


e.printStackTrace();


}


return null;


}


}


Below is an example use of the MyClassLoader.


public static void main(String【】 args) throws


ClassNotFoundException,


IllegalAccessException,


InstantiationException {


ClassLoader parentClassLoader = MyClassLoader.class.getClassLoader();


MyClassLoader classLoader = new MyClassLoader(parentClassLoader);


Class myObjectClass = classLoader.loadClass("reflection.MyObject");


AnInterface2 object1 =


(AnInterface2) myObjectClass.newInstance();


MyObjectSuperClass object2 =


(MyObjectSuperClass) myObjectClass.newInstance();


//create new class loader so classes can be reloaded.


classLoader = new MyClassLoader(parentClassLoader);


myObjectClass = classLoader.loadClass("reflection.MyObject");


object1 = (AnInterface2) myObjectClass.newInstance();


object2 = (MyObjectSuperClass) myObjectClass.newInstance();


}


Here is the reflection.MyObject class that is loaded using the class loader. Notice how it both extends a superclass and implements an interface. This is just for the sake of the example. In your own code you would only have to one of the two - extend or implement.


public class MyObject extends MyObjectSuperClass implements AnInterface2{


//... body of class ... override superclass methods


// or implement interface methods


}


转自:

相关文章
|
存储 Java 索引
用Java语言实现一个自定义的ArrayList类
自定义MyArrayList类模拟Java ArrayList核心功能,支持泛型、动态扩容(1.5倍)、增删改查及越界检查,底层用Object数组实现,适合学习动态数组原理。
743 4
|
IDE JavaScript Java
在Java 11中,如何处理被弃用的类或接口?
在Java 11中,如何处理被弃用的类或接口?
573 5
|
编解码 Java 开发者
Java String类的关键方法总结
以上总结了Java `String` 类最常见和重要功能性方法。每种操作都对应着日常编程任务,并且理解每种操作如何影响及处理 `Strings` 对于任何使用 Java 的开发者来说都至关重要。
712 5
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
786 1
|
Java Go 开发工具
【Java】(8)正则表达式的使用与常用类分享
正则表达式定义了字符串的模式。正则表达式并不仅限于某一种语言,但是在每种语言中有细微的差别。
708 1
|
存储 Java 程序员
【Java】(6)全方面带你了解Java里的日期与时间内容,介绍 Calendar、GregorianCalendar、Date类
java.util 包提供了 Date 类来封装当前的日期和时间。Date 类提供两个构造函数来实例化 Date 对象。第一个构造函数使用当前日期和时间来初始化对象。Date( )第二个构造函数接收一个参数,该参数是从1970年1月1日起的毫秒数。
459 0
|
JSON 网络协议 安全
【Java基础】(1)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
700 1
|
算法 Java 程序员
论文翻译 | 【深入挖掘Java技术】「底层原理专题」深入分析一下并发编程之父Doug Lea的纽约州立大学的ForkJoin框架的本质和原理
本文深入探讨了一个Java框架的设计、实现及其性能。该框架遵循并行编程的理念,通过递归方式将问题分解为多个子任务,并利用工作窃取技术进行并行处理。所有子任务完成后,其结果被整合以形成完整的并行程序。 在总体设计上,该框架借鉴了Cilk工作窃取框架的核心理念。其核心技术主要聚焦于高效的任务队列构建和管理,以及工作线程的管理。经过实际性能测试,我们发现大多数程序的并行加速效果显著,但仍有优化空间,未来可能需要进一步研究改进方案。
408 3
论文翻译 | 【深入挖掘Java技术】「底层原理专题」深入分析一下并发编程之父Doug Lea的纽约州立大学的ForkJoin框架的本质和原理
|
SQL Java 数据库连接
Java从入门到精通:3.1.2深入学习Java EE技术——Hibernate与MyBatis等ORM框架的掌握
Java从入门到精通:3.1.2深入学习Java EE技术——Hibernate与MyBatis等ORM框架的掌握
393 1
|
Java 测试技术 API
【Java技术深入解析】「核心技术提升」最流行的Java模拟框架Mockito入门指南(Java单元测试)
还在使用 Mockito 1.x?看看 Mockito 2 有哪些新功能!Mockito 3 没有引入任何破坏性的 API 变动,但现在需要 Java 8 而不是 Mockito 2 的 Java 6。 Mockito 4 删除了过时的 API。Mockito 5 将默认 mockmaker 改为 mockito-inline,现在需要 Java 11。一次只支持一个主要版本,而且不会向旧版本回传更改内容。
831 0
【Java技术深入解析】「核心技术提升」最流行的Java模拟框架Mockito入门指南(Java单元测试)