Try {// obtain the Class Object Class c = Class. forName ("full class name"); Object yourObj = c. newInstance (); // obtain Method methlist [] = cls. getDeclaredMethods (); for (int I = 0; I <methlist. length; I ++) {Method m = methlist [I];} // obtain the method object. Assume that the Method parameter is an int and the Method name is setAge method sAge = c. getMethod ("setAge", new Class [] {int. class}); // obtain the parameter Object [] arguments = new Object [] {new Integer (37)}; // execute the sAge method. invoke (yourObj, arguments);} catch (Exception e ){}
GetDeclaredMethod * () obtains all methods declared by the class, including public, protected, and private methods.
GetMethod * () obtains all the common methods of the class. This includes all the public methods of the class and all the public methods inherited from the base class and implemented from the interface.
Test example
package com.sf.test;
import java.lang.reflect.Method;
public class RefTest {
public static void main(String args[]) throws Exception { Class clazz = Class.forName("com.sf.test.Test"); Object object = clazz.newInstance(); Method refTest = clazz.getDeclaredMethod("refTest"); Method refTest1 = clazz.getDeclaredMethod("refTest1",String.class); refTest1.invoke(object, "0021212"); refTest.invoke(object); } }
package com.sf.test;
public class Test { public Test(){ } public void refTest() { System.out.println("00000000"); } public void refTest1(String string) { System.out.println(string); }}