我正在尝试使用反射来调用方法(增加字段的值)。但是,一旦调用该方法并打印值字段,它似乎无法更改。
public class Counter {
public int c;
public void increment() { c++; }
public void decrement() { c--; }
public void reset() { c = 0; }
}
在另一个班级:
public static void main(String[] args) {
// TODO Auto-generated method stub
String classInput;
String methodInput;
boolean keepLooping = true;
try {
System.out.println("Please enter a class name:");
classInput = new BufferedReader(new InputStreamReader(System.in)).readLine();
// loads the class
Class c = Class.forName(classInput);
// creating an instance of the class
Object user = c.newInstance();
while(keepLooping){
//prints out all the fields
for (Field field : c.getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
Object value = field.get(user);
System.out.printf("Field name: %s, Field value: %s%n", name, value);
}
//prints out all the methods that do not have a parameter
for(Method m: c.getMethods()){
if (m.getParameterAnnotations().length==0){
System.out.println(m);
}
}
System.out.println("Please choose a method you wish to execute:");
methodInput = new BufferedReader(new InputStreamReader(System.in)).readLine();
Method m = c.getMethod(methodInput, null);
m.invoke(c.newInstance(), null);
}
}
catch(Exception e){
e.printStackTrace();
}
答案 0 :(得分:0)
您总是使用新实例调用该方法,而不是您正在显示的实例
m.invoke(c.newInstance(), null);
所以你的user
对象保持不变。
而是使用您在开始时创建的对象,并在每次要invoke
Method
时传递它。
m.invoke(user, null);