我正在尝试使用反射来调用一个方法(增加字段的值)。但是,一旦调用该方法并打印值字段,它似乎并没有改变。
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();
}