Way to use a method as parameter

Hi I’ve been Looking for a way to create a method wich uses an other method for calculating stuff. As I surfed I found that there are methods in specific classes wich can do this for Example in the Library java.awt.event.ActionListener, where you can add a actionListener to a JButton.
It works like this:

button.addActionListener(new ActionListener(){
void ActionPerformed(ActionEvent e){
  // your code stuff
}
}

and my question is:
Is there any way of creating a method doing something like that?
I found something about this Topic but Nothing helped me.

1 Like

Sorry I copied the wrong link! The second selected the wrong message!

You can edit your post, if you posted something wrong.

As for what you are looking for… you are looking for a way to use any method as a Parameter, correct? If so, try using java.lang.reflect.Method class as a parameter. It does pretty much all you are looking for, if i got you right. :wink:

Edit :

I might be mistaken, but i think this line :

private transient volatile AccessControlContext acc =
        AccessController.getContext();

In the AWTEvent class is what takes the method as an object, though that might be wrong… but that‘s as far as i was able to trace the way of that Code back… So it could actually be anything within AWTEvent class… well, i think it‘s this one. :sweat_smile:

1 Like

Thenk you for the help but could you make a concrete example?

Never mind my last answer, actually the best approach seems to be using lambda expressions in your case. But they are pretty complicated.

As for an example :

float a = 37;

void setup() {
   size(600,400);
}

void draw() {
   printTest(new Test());
   printTest(new Test() {
      void myMethod(float v) {
         println(v + 7);
      }
   });
}

interface Test {
   void myMethod(float v);
}

class ActualTest implements Test {
   void myMethod(float v) {
      println(v);
   }
}

void printTest (Test t) {
   t.myMethod(a);
}

Though a better example is here :

https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

1 Like