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
ode { font-family: Courier New, Courier; font-size: 10pt; margin: 0px; }–>
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”); } 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
Tags
License
This work is published under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 License.







Leave a Reply