Is there a way to pass a method reference in Java?

2019-07-16 02:57发布

This is quite difficult to phrase, but I need to be able to link a specific method to an object. More specifically, I'm making a graphics-oriented GUI, and I want to be able to assign an arbitrary method as the default "action" function for an element, such as a button.

That is, I created these interfaced "graphics" objects that basically have the ability to draw themselves. I would like them to handle their own actions, so I can, for example, do something like this:

GraphicObject b1 = new Button();
GraphicObject b2 = new Button();
b1.assignDefaultAction(---some method reference here--);
b2.assignDefaultAction(---a different method reference here--);

Then, if I do something like:

b1.action();
b2.action();

Each element will call its own referenced method independently. I believe this is possible to do in C++, but I haven't seen it in Java. Is it even possible, or is there some kind of a workaround? The thing I'm trying to avoid is having to create specific abstraction for every single little thing I need to do, or litter my containing JPanel with a hundred specifications that just look messy.

Thank you for all your help.

4条回答
三岁会撩人
2楼-- · 2019-07-16 03:38

Buttons should use ActionListener implementations. Stick with Swing in that particular case.

Your own classes can follow suit and start with a Command pattern interface:

public interface Command {
    public void execute(Map<String, Object> parameters); 
}

Or maybe a better idea is to stick with the API that the JDK provides and try Callable.

查看更多
叛逆
3楼-- · 2019-07-16 03:39

There are no method references in Java. Instead you can use pseudo-closures (aka anonymous inner classes). The only problem with this is of course, you can't reuse the functions if needed.

查看更多
劫难
4楼-- · 2019-07-16 03:40

Beginning with Java 8 there will be easy-to-use method references and lambda expressions.

Assigning actions to buttons is actually a prime example.

 bttnExit.setOnAction((actionEvent) -> { Platform.exit(); });

or, using method references:

 bttnExit.setOnAction(MyClass::handleExitButton);
查看更多
仙女界的扛把子
5楼-- · 2019-07-16 03:41

Normally you'd just use an ActionListener anonymous inner class to do this, and add whatever method calls you want in the actionPerformed method.

Something like:

b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent a) {
        b.someMethod();
    }               
});
查看更多
登录 后发表回答