Tuesday, January 01, 2008

MyClassLoader - Java ClassLoader

I am very new to Java and often terms like ClassLoader, Virtual Machine scares me before start. With little of courage I start reading some of the documents on ClassLoader and ahh I find it very simple. Actually with reply to some of my old blog's comment, we had made a statement that "you can have your own classLoader in java".

The good part about ClassLoader - its written in Java :-). So one can expect code to be simple and more understandable than written in C++.

ClassLoader is nothing but a part of Java Virtual Machine responsible to load classes into memory. From where ? From local hard drive(mostly), from network and in some cases from browser. Little complex yet beautiful part of it is it load classes on demand not all at once. Java has an excellent feature to write your own classLoader which extends to ClassLoader class. Here, I named it as MyClassLoader :-). But if JVM has a classLoader why to write another one ? In my case, just for fun :D but there are other uses. One I got, is to automatically verify digital signature before invoking untrusted code. Second and more important when you want to update class at runtime. So, in this case we need to create another instance of our classLoader and then we can replace the already loaded classes with new updated classes. We can see some other usages as we move on to the blog.

I start reading some code here and there of classLoader from openjdk. If you have openjdk on your system, I will better suggest to go through some of the API implementation of ClassLoader. You will get the ClassLoader.java at path \jdk\src\share\classes\java\lang\ClassLoader.java. I was surprised to see that very less changes has been made to this file after jdk 1.2 and a great enhancement is done on jdk 1.2. In the code, you can see most of the API's have written in 1.2 only.

When java got released the most exciting and eye catching feature is how it execute code on the fly from remote server. Some kind of magic ? Yes, this magic is possible because java has the ability to write a custom classloader. The magic is this - in appletviewer/browser instead of looking into local had disk for classes it looks for remote server, loads the raw data through http and turns them into classes(duty of method called defineClass in ClassLoader, we will see this in more detail) inside Virtual Machine.

I am still in the midway of many document, reading re-reading and trying to understand more of it. We will try to see some of the method(s) which we need to implement for our custom ClassLoader, MyClassLoader. Most of the methods sounds easy but some methods like defineClass which is actually converting raw data into classes may go little complex.

No comments: