Java ClassLoader 1

Class

1
2
3
4
5
6
7
8
9
10
11
12
13
public abstract class ClassLoader {
...
protected final Class<?> defineClass(String name, byte[] b, int off, int len)
...
public Class<?> loadClass(String name) {...}
...
public final ClassLoader getParent() {...}
...
public URL getResource(String name) {...}
...
public Enumeration<URL> getResources(String name) {...}
...
}
  • Most important method is loadClass(arg) ,
    it accept a class’s full name, and return it’s instance.

  • defineClass(arg) accept a byte array, turn it into instance.
    Usually, it load a file from disk, then pass file byte into JVM.
    Instantiate Class into a instance through JVM’s(native method) define to Class.

  • getResource() and getResources search URL from repository.
    They have agent mechanism as well as loadClass, like:
    defineClass(getResource(name).getBytes())

Code

Because Java late binding and explain character,
Classes’ will be load when it needed like
static method/ construct method or direct allocate in field.

1
2
3
4
5
6
public class A {
public void xxx() {
B b = new B();
b.xxoo();
}
}

They are same when B have default constructor.

1
2
3
4
B b = new B();

B b = Class.forName("B", false,
A.class.getClassLoader()).newInstance();