2

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.

2
  • perhaps you could create an enum that represent each function() then pass that? Commented Dec 23, 2012 at 20:52
  • The way you can handle it in Java now (without lambda's in JDK8) is to implement Command or Strategy design pattern Commented Dec 23, 2012 at 20:58

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

We all hope for such features in the next java version, whenever it will come.
0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.