开发者

Set dynamic parameter value into generic method of Java Reflection

I'm a new java developer, and I want to develop my code with reflection. I have a class call User:

I want to pass dynamic value to those 3 methods, so in java reflection I got some code but I don't understand why?

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]);
}


I don't dare to ask why you wanna do this... this way but i hope this example helps you get the feeling of some of the capabilities of reflection provided by 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 + "]";
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜