Home > Enterprise >  Is there a similar method like the Function class's `apply` for the `Method` class?
Is there a similar method like the Function class's `apply` for the `Method` class?

Time:10-05

I tried using function.apply(object), but I'm actually looking for something like method.apply(object) (using the Method class instead of the Function class ).

I'm trying to do something like this:

public void Something(Function func){
    object.func();
}

where object has a method func, something like this:

public class object {
    public void func(){
        //long code
    }
}

Is there a method/function of Method similar to the apply method of Function?

I get the Method and I'm trying to do something like this:

public void anotherFunction(Method method){
    method.apply(object) //something like this
}

CodePudding user response:

Yes, what you're looking for is the invoke() method on the `Method class

Here's an example (is not pretty)

import java.lang.reflect.*;
class SomeObject {
  public void func() {
    System.out.println("long code");
  }
}
class Main {

  Object o = new SomeObject();
  public void run() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    var m = o.getClass().getMethod("func");
    anotherFunction(m);
  }

  public void anotherFunction(Method method) throws IllegalAccessException, InvocationTargetException {
    method.invoke(o);
  }
  public static void main(String ... args) throws NoSuchMethodException , IllegalAccessException, InvocationTargetException {
    Main main = new Main();
    main.run();
  }
}
Output: `long code`

It's just an example, in reality reflection should be more carefully used.

  • Related