Tuesday, February 3, 2009

ClassLoader - JAVA - How to load class from network at run time


Some points which may be helpful when you are working on java classloader.

If you are getting the security exception in your classloader file, just cross check these things
try {
String url = "http://localhost:8085/Classloader/com.jar";
String className ="com.cloader.Intermediate";
//This commented line may not work and give you security exception,so don’t use this
// Always use newInstance().
//URLClassLoader loader =URLClassLoader.newInstance(new URL[]{new URL(url)});
URLClassLoader loader =URLClassLoader.newInstance(new URL[]{new URL(url)});
Class aclass = loader.loadClass(className);
//Object object = aclass.newInstance();
//Uncomment above line as per your need.
//Here getImageResource() is my own method which will return the image object.
Image img = getImageResource(this, image.png");
//Here getInputStream()is my own method which will return the FileInputStream objrct
FileInputStream fis = getInputStream();
//Below getInstance() is the static method present inside the Intermediate class.
//Which is look like this
// public static Intermediate getInstance(FileInputStream fis){}
Method method = aclass.getMethod("getInstance", new Class[]{fis.getClass(),
Image.class});
// Don’t set setAccessible(true) it might be give you security error. So I am commenting it here
//method.setAccessible(true);
method.invoke(null, new Object[]{fis, img});
} catch (Exception e) {}
=========================================================
Some More about class loaders:
**
If your method is static then you don’t need to pass the object Instance during the method invoke. Just pass the first parameter as null. See below:
method.invoke(null, new Object[]{fis, imgWelcome});
Otherwise you need to create the Instance of class and then pass it Like this:
Object object = aclass.newInstance();
method.invoke(object, new Object[]{fis, img});
** I am not sure the content on the server (jar file) always need to be signed or not, to achive all functionality on loacal system (To get more freedom outside of JDK shandbox), but currently I am signing it.
**
Normally You can’t read the file present on the local system through the code being load by class loader from the network.
ClassLoader? What it does?
The JVM default class loader load classes from the local file system by it self, but if you are creating applications that are capable of loading classes from remote servers? Class loaders can do that. Class loaders can also be used to ensure safety and security of byte codes; for example, you can develop a custom class loader capable of checking a digital signature before executing untrusted foreign code.
For more details visit to:
This article is just a quick review of class loaders. If you have any issue or if you are finding any issue with this article please let me know :)

No comments:

Post a Comment