- Class World library is used for java class loading.It provides a set of classes and method to configure and manage the class files.
- This library also provides loading a class file from a remote jar.
- API download link :-
http://classworlds.codehaus.org/releases.html
Project Structure:-
The Target Jar for Loading :-
- This jar file we need to load through class world.
- The jar project structure:-
- The method printName is,
package com.sandeep.some.lib;
public class NumberWork {
public static String printName(String name){
return "Hi I am "+name+" inside Demo Java Library jar";
}
}
- Jar File download link :-
https://docs.google.com/open?id=0B2Iq42FA1tljbFdBaHhjSDVZOVU
Testing the Class Loader:-
ClassWorldDemo.java ,
package com.sandeep.classworld.demo;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import org.codehaus.classworlds.ClassRealm;
import org.codehaus.classworlds.ClassWorld;
import org.codehaus.classworlds.DuplicateRealmException;
public class ClassWorldDemo {
public static void main(String[] args) {
ClassWorld world = new ClassWorld();
ClassRealm containerRealm = null;
try {
containerRealm = world.newRealm( "demoRealm" );
URL jarUrl = new URL("file:///D://MyDocuments//blogs//DemoJavaLibrary.jar");
containerRealm.addConstituent(jarUrl);
Class loadedClass = containerRealm.loadClass("com.sandeep.some.lib.NumberWork");
System.out.println(loadedClass.getCanonicalName());
Method[] listOfMethods = loadedClass.getMethods();
Method amethod = listOfMethods[0];
String output = (String) amethod.invoke(null, "Sandeep");
System.out.println("The method in jar returns : "+output);
} catch (DuplicateRealmException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
Output:-
com.sandeep.some.lib.NumberWork
The method in jar returns : Hi I am Sandeep insideDemoJavaLibrary jar
Code Download :-