将动态参数值设置为Java Reflection的泛型方法



我是一个新的java开发人员,我想用反射来开发我的代码。我有一个类调用User:

我想传递动态值给这3个方法,所以在java反射我得到了一些代码,但我不明白为什么?

import .....
public class user
{
   private int id;
   private String name;
   private Date dob;
   public setID(int id)
   {
      this.id = id;
   }
   public setName(String name)
   {
      this.name = name;
   }
   public setDOB(Date dob)
   {
      this.dob = dob;
   }
}
Class cls = Class.forName("user");
Method[] methods = cls.getDeclearedMethod();
for(Method m : methods)
{
   Object[] args = new Object[1];
   args[0] = .....
   m.invoke(cls, args[0]);
}

我不敢问你为什么要这样做…但是我希望这个例子能帮助你感受Java提供的一些反射功能。

import java.lang.reflect.Method;
import java.util.Date;
public class Ref {
    public static void main(String[] args) throws ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        Class cls = Class.forName("User");
        Object o = cls.newInstance();
        Object[] fieldValues = { new Integer(1), "", new Date() };
        Method[] methods = cls.getDeclaredMethods();
        for (Method m : methods) {
            Class[] paramTypes = m.getParameterTypes();
            Object[] paramValues = new Object[1];
            if (paramTypes.length == 0) {
                continue;
            }
            if (paramTypes[0].equals(Date.class)) {
                paramValues[0] = new Date();
            } else if (paramTypes[0].equals(String.class)) {
                paramValues[0] = "nice";
            } else if (paramTypes[0].equals(Integer.TYPE)) {
                paramValues[0] = 2;
            }
            if (paramValues[0] != null) {
                try {
                    m.invoke(o, paramValues[0]);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } // end for
        } // end for
        System.out.println("o = " + o);
    } // end method main
} // end class Ref
class User {
    private int id;
    private String name;
    private Date dob;
    public void setID(int id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setDOB(Date dob) {
        this.dob = dob;
    }
    public String toString() {
        return "[id = " + id + ", name = " + name + ", date = " + dob + "]";
    }
}

相关内容

  • 没有找到相关文章

最新更新