0

我正在尝试使用反射来调用一个方法(增加字段的值)。但是,一旦调用该方法并打印值字段,它似乎并没有改变。

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();

    }
4

1 回答 1

0

您总是使用新实例调用该方法,而不是您正在显示的那个

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

所以你的user对象保持不变。

而是使用您在开始时创建的对象,并在每次需要时将其传递invokeMethod.

m.invoke(user, null);
于 2013-10-11T02:23:34.133 回答