Java 反射机制运用实例(动态调用类的方法)

    技术2026-08-03  2

    TIP:只知道类名,要运用反射机制动态调用已知类名的方法

    类结构:

    -------form(package):CityQueryForm.java

    -------test(package):Test.java

     

    CityQueryForm.java:

    package form;

    import java.util.Hashtable;

    public class CityQueryForm {  private String name = null;  public void setName(Hashtable ht) {  this.name = (String) ht.get("name"); }  public String getName() {  return name; }

    }

     

     

    Test.java:

    package test;

    import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.Hashtable;

    public class Test {

     private void getForm(Hashtable ht, String formName) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {    //Class c = Class.forName(formName);  Object o = Class.forName(formName).newInstance();  // 指定类名的类对象    Class partypes[] = new Class[1];  partypes[0] = Hashtable.class;  //setName方法需要的参数

        Method ms = o.getClass().getMethod("setName", partypes); //得到指定方法名和参数的方法对象  Method mg = o.getClass().getMethod("getName", null);    ms.invoke(o, ht);  //方法调用  String mg.invoke(o, null);  System.out.println(name); }

     public static void main(String[] args) throws ClassNotFoundException, SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {    String formName = "form.CityQueryForm";    Hashtable ht = new Hashtable();  ht.put("name", "wuhan");    Test t = new Test();  t.getForm(ht,formName);

     }

    }

    测试结果:

    wuhan

    最新回复(0)