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?
Method#invoke()javadoc. It answers both your questions.Methodclass and its methods here.