Get Off My Lawn
Get Off My Lawn

Reputation: 36299

Java Function as Parameter

I am trying to add key press events to my library, so is it possible to pass a function as a parameter to one of my library's classes, then when my library needs to fire off that function?

example:

Library lib = new Library();
lib.myAction(function(){
    // Do some java stuff here
});

So with that, when my library see something take place, such as a key press, it will fire off that function. If you have every worked with JavaScript you can do this (Really common with jQuery), and I would like to have the same effect but with Java.

Upvotes: 2

Views: 181

Answers (2)

ovunccetin
ovunccetin

Reputation: 8663

There is no simple way for this in Java. However you can pass a Method object (the method must be static) to your myAction function and invoke the passed method in it as follows:

public Object myAction(Method m, Object... args) {
    return m.invoke(args);
}

Note that the args parameter is the parameter list of the passed method.

For example, suppose you have a class A and a static method sampleMethod(String s) defined in A. You can call your myAction method as follows:

lib.myAction(A.class.getMethod("sampleMethod", String.class), "Value of parameter s");

If your sampleMethod is parameterless then you can omit the second parameter:

lib.myAction(A.class.getMethod("sampleMethod", String.class));

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500055

No, there's no direct equivalent of that in Java. The closest you can get is to have an interface or abstract class, and then use anonymous inner class to implement/extend it:

lib.myAction(new Runnable() {
    @Override public void run() {
        // Do something here
    }
});

This should be made much simpler by Java 8's lambda expression support.

Upvotes: 7

Related Questions