Rajmahendra's Blog
« Home | Welcome to my blog »
Thursday, April 27, 2006
Sample program for Log4J and Class Loader
Following is the program I tryed recently to learn Class Loader and Log4J.
Really good program simple to write and easy to understand.
Please provide your comment.
If you cant understand, Let me know
package com.test.loader;
import java.lang.reflect.Method; import org.apache.log4j.Logger;
public class MyClassLoader {
public static Method findMethod(String name,Method methods[])
{
Method method = null;
for (int i=0; i < methods.length; i++)
if (methods[i].getName().equals(name))
{
method=methods[i];
i = methods.length;
}
return method;
}
public static void main (String args[])
{
Logger log = Logger.getLogger(MyClassLoader.class);
String cls = "com.test.loader.TestClass";
String mtd = "sayHaiTo";
Object objClass = null;
try
{
log.debug(cls +" class goint to be loaded");
Class clazz = Class.forName(cls);
objClass = clazz.newInstance();
log.debug("Loading class success : " + cls );
Method methods[] = clazz.getMethods();
log.debug(methods.length + " Methods found for " + cls );
for (int i=0; i < methods.length; i++)
log.debug( i+1 + ") " + methods[i].getName());
log.debug("Finding Method '" + mtd + "' in class '"+cls+"'");
Method method = findMethod(mtd,methods);
if (method == null)
log.warn("Method '" + mtd + "' not found in class '" + cls + "'");
else
log.info("Method '" + mtd + "' found in class '" + cls + "'");
log.debug("invoking Method '" + mtd + "' in class '" + cls + "'");
method.invoke(objClass,new String[]{"Ram"});
log.debug("initializing method sayMyAge");
Method method1 = findMethod("sayMyAge",methods);
log.debug("calling method sayMyAge"); method1.invoke(objClass,new Object[]{new Integer(25)});
}
catch(ClassNotFoundException e)
{
log.error("Loader class '" + cls + "' Not Found.");
}
catch(IllegalAccessException e)
{
log.error("Illegal Access of class '" + cls + "' .");
}
catch(Exception e)
{
log.error("Exception in class '" + cls + "' Invocation. Thrown : " + e.getMessage());
} } }
|
Technorati Tags: Java java tools
Add a comment