Java 有没有办法传递方法引用?
这很难表达,但我需要能够将特定方法链接到对象。更具体地说,我正在制作一个面向图形的 GUI,并且我希望能够指定任意方法作为元素(例如按钮)的默认“操作”功能。
也就是说,我创建了这些接口的“图形”对象,它们基本上具有绘制自身的能力。我希望它们能够处理自己的操作,因此我可以执行以下操作:
GraphicObject b1 = new Button();
GraphicObject b2 = new Button();
b1.assignDefaultAction(---some method reference here--);
b2.assignDefaultAction(---a different method reference here--);
然后,如果我执行以下操作:
b1.action();
b2.action();
每个元素将独立调用其自己的引用方法。我相信这在 C++ 中是可能做到的,但我还没有在 Java 中看到过。这是否可能,或者是否有某种解决方法?我试图避免的事情是必须为我需要做的每一件小事创建特定的抽象,或者在我的 JPanel 中乱扔一百个看起来很混乱的规范。
感谢您的帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
按钮应使用
ActionListener
实现。在这种特殊情况下坚持使用 Swing。您自己的类可以效仿并从命令模式接口开始:
或者更好的想法是坚持使用 JDK 提供的 API 并尝试 可调用。
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:
Or maybe a better idea is to stick with the API that the JDK provides and try Callable.
Java 中没有方法引用。相反,您可以使用伪闭包(又名匿名内部类)。当然,唯一的问题是,如果需要,您无法重用这些函数。
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.
通常,您只需使用 ActionListener 匿名内部类来执行此操作,并在 actionPerformed 方法中添加您想要的任何方法调用。
像这样的东西:
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:
从Java 8开始,将出现易于使用的方法引用和 lambda 表达式。
将操作分配给按钮实际上就是一个很好的例子。
或者,使用方法参考:
Beginning with Java 8 there will be easy-to-use method references and lambda expressions.
Assigning actions to buttons is actually a prime example.
or, using method references: