有没有办法在Java中传递方法引用? [英] Is there a way to pass a method reference in Java?

查看:191
本文介绍了有没有办法在Java中传递方法引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很难说清楚,但我需要能够将特定方法链接到对象。更具体地说,我制作了一个面向图形的GUI,并且我希望能够为一个元素(比如按钮)指定一个任意方法作为默认的action函数。



也就是说,我创建了基本上可以绘制自己的接口图形对象。我希望他们处理他们自己的行为,例如,我可以这样做:

按钮();
GraphicObject b2 = new Button();
b1.assignDefaultAction(---这里有一些方法参考 - );
b2.assignDefaultAction(---这里有一个不同的方法参考 - );

然后,如果我做了类似的事情:

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

每个元素都会独立调用自己的引用方法。我相信这是可以在C ++中完成的,但我没有在Java中看到它。它甚至有可能,还是有某种解决方法?我试图避免的事情是必须为每一件我需要做的事情创建特定的抽象,或者用一百个规格乱七八糟的包含JPanel的东西来看看。


解决方案

按钮应该使用 ActionListener 实现。



您自己的类可以效仿并从Command模式界面开始:

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

或者更好的办法是坚持JDK提供的API尝试 Callable


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.

解决方案

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.

这篇关于有没有办法在Java中传递方法引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆