Dynamically Loading A Class
Reflection is the mechanism to look and even modifiy the structure of a program by providing a window into the fundamentals of a language (classes,methods,fields) via Java API. Most of the tools we use works with Reflection.
Example: Tomcat looks up the class name in the web.xml file. Then loads the class dynamically on a web request. Class.forName(className) loads the class dynamically at runtime if not loaded. forName initializes the class and returns the Class object which contains the metadata of the class.
Methods are invoked with java.lang.refect.method.invoke().The first argument is object instance with which the method is invoked. If the method is static first argument must be null. Subsequent parameters are method parameters.
ArrayList returnList = null;
String s = cargo;
// Creating the class with
Class cls = Class.forName(className);
Object obj = cls.newInstance();
if(!"".equals(cargo)) {
// Class types[] determines the count of parameter type of the invoking method
Class types[] = new Class[1];
// types[0] determines the parameter type
types[0] = String.class;
// Object argList[] determines the count of parameter value
Object argList[] = new Object[1];
// argList[0] determines the parameter value
argList[0] = new String(s);
Method m = cls.getMethod(optName, types);
// Since invoking a static method first parameter should be null
returnList = (ArrayList) m.invoke(null, argList);
} else {
Method m = cls.getMethod(optName, null);
returnList = (ArrayList) m.invoke(null, null);
}
Comments
Post a Comment