2013-10-11 80 views
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(); 

    } 

回答

0

你總是調用方法用一個新實例,而不是一個你正在顯示

m.invoke(c.newInstance(), null); 

所以你user對象保持不變。

而是使用您在開始時創建的對象,並在每次要傳遞invoke時將其傳遞給Method

m.invoke(user, null); 
+1

謝謝!解決了問題:) – Dheeraj