Sunday, January 13, 2008

MyClassLoader - Java ClassLoader Final Part

Sorry as I am not able to proceed sequentially. But now its time for implementation. I have 3 java files with me:

1. myClassLoader.java which inherits from ClassLoader and implements the minimum requirement.

2. myClassLoaderMain.java which loads the class HelloWorld, making its instance and calling one of the method of it.

3. HelloWorld.java which is simply a program with one method.

myClassLoader is not doing any of the special job but at the end I am providing you the link of some more documents which can provide you special classLoader like one good article is showing you how to load class change on fly.

myClassLoader.java

import java.io.*;
import java.util.*;
public class myClassLoader extends ClassLoader {
private Hashtable classes = new Hashtable();
public myClassLoader(){
super(myClassLoader.class.getClassLoader());
}
public Class loadClass(String className) throws ClassNotFoundException {
return findClass(className);
}

public Class findClass(String className){
Class result=null;
result = (Class)classes.get(className);
System.out.println("Class Name is : " + className);
if(result != null){
return result;
}
try{
return findSystemClass(className);
}catch(Exception e){
return null;
}
}
}

myClassLoaderMain.java

public class myClassLoaderMain {
public static void main(String [] args) throws Exception{
myClassLoader test = new myClassLoader();
Object o = (test.loadClass("HelloWorld")).newInstance();
((HelloWorld)o).mymethod();
}
}

HelloWorld.java

class HelloWorld {
public void mymethod()
{
System.out.println("Atleast print this ");
}
public static void main(String[] args)
{
System.out.println("Hello World");
}
}

Now running all together:

javac *.java
java myMainClassLoader
/* It will call mymethod of HelloWorld */

If you are keen to move further and want to make some magical class Loader please check this articles:
1. Basics of ClassLoader on JavaWorld.
2. A look at Java ClassLoader - Here they made an example of loading class at runtime.
3. Java ClassLoader wiki page.

Any comments or correction or questions are most welcome.

No comments: