简体   繁体   中英

Invoking a method using reflection in Java

I am trying to use reflection to invoke a method (which increments the value of the fields). However, once the method is invoked and I print the values fields, it doesnt seem to change.

public class Counter {
    public int c;
    public void increment() { c++; }
    public void decrement() { c--; }
    public void reset() { c = 0; }
}

in a different class:

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

    }

You're always invoking the method with a new instance, not the one you are displaying

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

So your user object remains unchanged.

Instead use the object you created at the start and pass it every time you want to invoke the Method .

m.invoke(user, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM