一个类的三种形态:
- 源码(source)
- 字节码(class)
- 运行时(runtime)
package java.lang.annotation;
/**
* Annotation retention policy. The constants of this enumerated type
* describe the various policies for retaining annotations. They are used
* in conjunction with the {@link Retention} meta-annotation type to specify
* how long annotations are to be retained.
*
* @author Joshua Bloch
* @since 1.5
*/
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
ClassLoader,是类加载器的核心,而loadClass则是ClassLoader最核心的部分,通过此源码可查看到其使用双亲委派机制
- 同一时间只允许一个线程加载类(排他),利用synchronized
- 已加载过的类,不允许再次加载,没有被加载的才能够加载
- 父类能加载的,绝不交给子类加载
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
//同一时间只允许一个线程加载类
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded
Class<?> c = findLoadedClass(name);
//已加载过的类,不允许再次加载,没有被加载的才能够加载
if (c == null) {
long t0 = System.nanoTime();
try {
if (parent != null) {
c = parent.loadClass(name, false);
} else {
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found
// from the non-null parent class loader
}
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
long t1 = System.nanoTime();
c = findClass(name);
// this is the defining class loader; record the stats
sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
sun.misc.PerfCounter.getFindClasses().increment();
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
AppClassLoader > ExtClassLoader > BootstrapClassLoader
- 启动类加载器(Bootstrap ClassLoader):C++实现,在java里无法获取,负责加载/lib下的类。
- 扩展类加载器(Extension ClassLoader): Java实现,可以在Java里获取,负责加载/lib/ext下的类。
- 系统类加载器(Application ClassLoader):是与我们接触对多的类加载器,我们写的代码默认就是由它来加载,ClassLoader.getSystemClassLoader返回的就是它。
public class ClassLoaderTest { public static void main(String[] args) { ClassLoader cl = ClassLoaderTest.class.getClassLoader(); while (cl != null) { System.out.println(cl); cl = cl.getParent(); } } } 输出如下 sun.misc.Launcher$AppClassLoader@4e0e2f2a sun.misc.Launcher$ExtClassLoader@2a139a55