public Method[] getMethods()返回某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法。
public Method[] getDeclaredMethods()对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法。
public static void main(String[] args) throws ClassNotFoundException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { Bean bean = new Bean("QQ", 18); System.out.println(bean); //使用反射 String className = "com.my.test.Bean"; Classclas = (Class ) Class.forName(className); //生成一个实例 Bean b = (Bean)clas.newInstance(); b.setAge(20); b.setName("WW"); System.out.println(b); //调用方法 clas.getMethod("setName", String.class).invoke(bean, "Jerry"); clas.getMethod("setAge", int.class).invoke(bean, 25); System.out.println("After reflection....\n" + bean); }
【转】使用反射动态执行方法例子:
java利用反射动态执行类方法Person类 public class Person { String name; String day; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDay() { return day; } public void setDay(String day) { this.day = day; } public void printlinfo() throws RuntimeException, IOException{ System.out.println(name); System.out.println(day); String url="http://www.163.com"; openURL(url); } public void openURL (String url)throws RuntimeException,IOException{ String urlx=null; urlx="rundll32 url.dll,FileProtocolHandler "+url; Process p=Runtime.getRuntime().exec(""+urlx); } } 利用反映动态执行类的方法 public static void print(byte[] b1,String tname,String tday) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { MyClassLoade myClassLoader=new MyClassLoade(); Class c = myClassLoader.defineClass("Person", b1); System.out.println(c.getName()); Object object= c.newInstance(); Field[] fields=c.getDeclaredFields(); System.out.println(fields.length); String args="java.lang.String"; Method method1= c.getDeclaredMethod("setName", args.getClass()) ; method1.invoke(object,new Object[] {tname}); Method method2= c.getDeclaredMethod("setDay", args.getClass()) ; method2.invoke(object,new Object[] {tday}); Method method = c.getDeclaredMethod("printlinfo", null) ; method.invoke(object); } 参考:利用反射实现JavaBean的自动赋值 import java.lang.reflect.Method; import java.util.*; import javax.servlet.http.HttpServletRequest; import com.sns.exception.ApplicationException; public final class ParameterUtil { public static void setFormBean(HttpServletRequest request, Object bean) { Class c = bean.getClass(); Method[] ms = c.getMethods(); for(int i=0; i