我正在尝试在Java中创建自定义事件和监听器。 我已经查看了以下文章和问题:
https://www.javaworld.com/article/2077333/core-java/mr-happy-object-teaches-custom-events.html
但我仍然无法真正理解它。这是我想要完成的内容:我有一个String对象,其内容随程序运行而更改。我希望能够向该字符串添加侦听器,以监听它是否包含特定字符串,当它包含时运行一段代码。我想像这样使用它:
String string = "";
//String.addListener() and textListener need to be created
string.addListener(new textListener("hello world") {
@Override
public void onMatch(
System.out.println("Hello world detected");
)
}
//do a bunch of stuff
string = "The text Hello World is used by programmers a lot"; //the string contains "Hello World", so the listener will now print out "Hello world detected"
我知道可能有更简单的方法来完成这个任务,但我想知道如何用这种方式来实现。
谢谢@Marcos Vasconcelos指出,你不能向
String
对象添加方法,那么我可以像@Ben指出的那样使用自定义类吗?
EventString
(或其他名称),在其中拥有一个字符串对象,然后为其实现自定义事件监听器。 - BenMyEventListener
,其中包含一个方法onMyEvent
。然后在你的EventString
类中有一个addMyEventListener(MyEventListener)
方法,它保存了对监听器的引用。当发生任何你想要发生的事情时(例如,在你的setValue
方法中,值hello world
是参数),你就可以为你的监听器调用onMyEvent
方法。 - Ben