Class and static Method Reflection exampleFrom WikiJavabuy this book
In the example both the class and the method names are specified via strings. The method used in the example includes also a String parameter to be passed in and it returns another String.
the articleThis example is composed of two class files:
Inside the main method of Reflection you can notice the steps required:
note that:
DynamicallyPointedClass
package com.wikijava.reflection.pointed; /** * this is the dummy class containing a method it serves as example for the * reflection the class implements the method <b>method</b> that will be called * by the reflection procedures * * @author Giulio */ public class DynamicallyPointedClass { private static final String HELLO = "Hello "; //$NON-NLS-1$ /** * * simply gets a String and returns another String * * @param name * @return a String */ public static String method(String name) { return HELLO + name; } } Reflectionpackage com.wikijava.reflection; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * this example executes dynamically a method on a class, the class is * dynamically choosen via a string, and so is the method * * * @author Giulio */ public class Reflection { private static final String NAME = "Giulio"; //$NON-NLS-1$ private static final String METHOD = "method"; //$NON-NLS-1$ private static final String CLASS = "com.wikijava.reflection.pointed.DynamicallyPointedClass"; //$NON-NLS-1$ /** * @param args */ public static void main(String[] args) { Class<?> class1; try { class1 = Class.forName(CLASS); Method method = class1.getMethod(METHOD, String.class); Object o = method.invoke(null, NAME); System.out.println(o); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } }
|

Thanks i was looking for a way to call the static method of a class.
--Saurabh
--202.80.51.226 08:17, 25 March 2009 (UTC)