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.

Post a Comment:
Comments are closed for this entry.
About

Hi, I am Vaibhav Choudhary working in Sun. This blog is all about simple concept of Java and JavaFX.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today