我有以下代码,它允许我在扫描仪中输入我想要调用的 Employee getter 方法,它将使用反射来完成此操作(方法的名称不应出现在代码中的任何位置)。这适用于 getter 方法,但我现在需要修改代码以对 setter 方法执行类似的操作。过去一周我一直在试图弄清楚如何做到这一点,但我却做不到。任何帮助将不胜感激。
谢谢。
public static void main(String[] args) {
Employee e = Employee.testEmployee(); // a sample employee
Class cls = e.getClass();
Scanner scanner = new Scanner (System.in); // to parse data the user types in
String nextCommand;
// until the user enters "quit", get the next input from the user, and if it matches
// a given command, get the desired information from the employee object
do {
System.out.print("Enter command >> ");
nextCommand = scanner.next();
Method method = null;
try{
method = cls.getMethod(nextCommand);
}
catch(NoSuchMethodException x) {
}
try{
System.out.println(method.invoke(e));
}
catch(IllegalAccessException x) {
}
catch(java.lang.reflect.InvocationTargetException x) {
}
catch(NullPointerException x) {
}
} while (! nextCommand.equals("quit"));
}
最佳答案
这是一个代码示例,可以实现您想要实现的目标:
public class Test {
private static HashSet<Class<?>> classes = new HashSet<>();
static {
classes.add(String.class);
classes.add(Integer.class);
classes.add(GregorianCalendar.class);
}
public static void main(String[] args) throws NoSuchMethodException,
SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
X obj = new X();
obj.setField("lala");
Method method = obj.getClass().getMethod("getField", null);
System.out.println(method.invoke(obj, null));
Method setMethod = getWorkingMethod(obj);
setMethod.invoke(obj, "who let the dogs out");
System.out.println(obj.getField());
}
private static Method getWorkingMethod(Object obj) {
Method method = null;
for (Class<?> c : classes) {
try {
method = obj.getClass().getMethod("setField", c);
} catch (NoSuchMethodException | SecurityException e) {
continue;
}
if(method != null){
return method;
}
}
throw new IllegalArgumentException("No such method found!");
}
}
class X {
private String stringField;
public void setField(String s) {
stringField = s;
}
public String getField() {
return stringField;
}
}
输出:
lala
who let the dogs out
注释:
创建一个存储
HashSet
的集合(我使用Class<?>
)对象。您将使用它们来迭代可能性并查看是否存在具有该参数的方法。使用try-catch来查看方法是否存在(找不到则抛出异常)。
这对于重载方法不起作用。如果这是您的情况,您就必须做出调整。不过,我希望这不会有问题,因为你说这是针对 setter 的(通常没有重载)。
关于java - 通过反射调用带有参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20429943/