简体   繁体   中英

Invoking method using reflection

I am trying to figure out how to invoke a method of a custom class. Here is the process of what I am trying to do:

1) I initialize an array of methods from the list of methods of my custom class, and an empty List of Method which will be used to hold a filtered list of these methods.

Method method[] = MyClass.getDeclaredMethods();
List<Method> x = new ArrayList<Method>();

2) I then run my array of methods through a for loop and filter out whichever methods do not fill my required criteria.

 for (Method m : methods){
       if(...){
          if(...){
               x.add(m);
          }
       }
    }

3) Finally, I need to invoke each of the methods in the finalized list. This is where I am stuck, I am not exactly sure how the invoke function works. Here is what I am trying:

for(int i=0; i < x.size(); i++){
    boolean g = x.get(i).invoke();
        if(...)
        else(...)
}

The thing is, I know Exactly what it is I don't know, I am just having trouble finding the answers. These are the questions I need answered:

1) Which object will actually use the invoke function? Is it going to be, in my case, the particular method I want to invoke, or an instance of the class I am trying to invoke?

2) I know that the invoke function is going to require arguments, one of which is the parameter data for the method. What I am unclear about is what exactly the first argument needs to be. I am thinking that the first argument is the actual method itself, but then I run into a logical loop, because the way I have it coded has the method using the invoke function, so I am stumped.

3) In my case, the methods I wish to invoke don't actually take any parameters, so when I do happen to figure out how the invoke function works, will I need to set one of the arguments to null, or will I just omit that part of the argument list?

You're using .invoke incorrectly. See this short example:

public class Test {
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        X obj = new X();
        Method method = obj.getClass().getMethod("test", null);
        method.invoke(obj, null);
    }   
}

class X {
    public void test(){
        System.out.println("method call");
    }
}

Output:

method call

More information in the docs .

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.

You have never specified an object nor parameters. My sample uses no parameters so I can put null instead. But either way you have to provide an instance as the first parameter (unless it is static ).

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