0. Java’s Virtual Machine, Java Classes, and the CLASSPATH Variable
Class文件:由字节码组成,字节码文件运行在JVM上;默认情况下是由最后声明、最后加载的
ClassLoader加载。
ClassPath: 定位Class文件的位置。
1. Classloader Technology
类加载技术是基于分层的机制来处理Class文件的,Java集成了三种类型的ClassLoader:
■ Bootstrap classloader —Loads classes from the core Java libraries present in the lib
directory of your java home directory.
■ Extension(Sytem) classloader —Loads classes from the lib/ext directory of your Java
platform or any directory specified in the java.ext.dirs system property.
■ Application classloader —Loads classes based on the elements specified in the
application classpath.
1.1 Traditional use of classloaders in Java
These three classloaders are linked in a hierarchical relationship. In order to load a class,
a classloader first asks its parent if it’s able to load the class. If not,it tries to load the class
itself. This mechanism is used at each classloader level. In this situation,the same
classloaders are used to resolve all the classes of an application, which makes it difficult
to isolate the resolution of different classes.
1.2 The classloader inOSGi
OSGi technology provides a different approach to using classloaders; it’s not based on a
hierarchical approach but on the concept of classloader chaining(这些ClassLoader是OSGi
管理的), which allows fined-graine(细粒度) control of the visibility of classes from each other.
In this context, each component is associated with a dedicated classloader. According to
the component configuration, this classloader is linked to other components’ classloaders
for the resolution of classes outside the current component. Having classloaders
dedicated to components makes isolation between components possible, and, by default,
no class can be seen outside a component.
Instead, you need to explicitly import and export them by configuring the corresponding
packages in the manifest files.
2. JSR 294—Java module system
JSR 294 aims to provide a static module system inside Java itself. The JSR is based on a
similar approach to the OSGi Require-Bundle header but with a greater emphasis on
language support and the runtime modularity of the JDK itself. JSR 294 doesn’t have the
same support as OSGi to make different versions of the same class cohabit in the same
process.
3. OSGi类加载的优点
(1) Bundle之间可直接共享类,不需要将一个JAR文件提升为一个Parent Class Loader.
(2) 同一时间可部署同一个类的不同版本,而不冲突。