gpt4 book ai didi

java - 将动态参数值设置为Java反射的泛型方法

转载 作者:行者123 更新时间:2023-12-01 15:42:52 27 4
gpt4 key购买 nike

我是一名新的 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]);
}

最佳答案

我不敢问你为什么要这样做......这样但我希望这个例子可以帮助你感受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 + "]";
}
}

关于java - 将动态参数值设置为Java反射的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7735151/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com