我是一名新的java开发人员,我想用反射开发我的代码。 我有一个班级用户:
我想将动态值传递给这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]);
}
答案 0 :(得分:1)
我不敢问你为什么要这样做......这样我希望这个例子可以让你感受到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 + "]";
}
}