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

て烟熏妆下的殇ゞ 提交于 2019-12-11 01:41:01

问题


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.


回答1:


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.




回答2:


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.




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/9338193/is-there-a-way-to-pass-a-method-reference-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!