0
我想用反射來調用一個方法(它增加了字段的值)。但是,一旦調用方法並打印值字段,它似乎不會改變。在Java中使用反射調用方法
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();
}
謝謝!解決了問題:) – Dheeraj