Friday, January 06, 2006

Class Loader

(1) All app has at least 3 class loader

a. bootstrap class loader (C implemented ClassLoader part of JVM for rt.jar)

therefore, Integer.class.getClassLoader() always return "null"

Java Implementation Class Loader
b. extension class loader ( does not use class path) extended from URLClassLoader

Normally, do not place jar in extenstion class dir jre/lib/ext

c. system (application) class loader use class patth extended from URLClassLoader

(2) Class Loader is parent/child relationship

any class loader exception bootstrap class loader has a parent class loader

whenerver current class loader is asked to load foo.class, it ask it's
parent system (app) class loader, extension class loader and bootstrap ]
class loader. If any of the parent loaded the class, it will not be loaded
again.

For class loading, the rule is that always do "delegate" class loading.
Delegate to parent first. Otherwise customer class loader may accidently
load a version of system class that bypass the important security check
The good customer class loaders are Applet, Servlet, and RMI stubs


Any customer class loader can be written for special purpose. However,
customer class loader should carry out specialized secutiry check. For
instance, a class loader can refuse to load a class has not been marked
with "Paid"

(3) to load a class by current class loader

foo.class.forName()


However, if your library create your own Class.forName(), or current application
is loaded by different classloader than the classloader loaded the foo.class
or loaded class is not visiable from the class loader that load library

Thread curThread = Thread.currentThread();
ClassLoader loader = curThread.getContextClassLoader();
Class clazz = loader.loadClass(className);

(4) a class loader to load encrypted classes

public fooClassLoader extends ClassLoader

{

protected Class findClass(String name) throws ClassNotFindException
{
byte[] classBytes = loadClassByBytes(name); // load byte code

Class clazz = defineClass(name, classBytes,0 classBytes.length); // present byte code to JVM, defineClass is in the supper ClassLoader class

if(clazz == null)
throw new ClassNotFoundException(name);

return clazz;

}

}

No comments: