Java - 创建自定义事件和侦听器

时间:2018-03-19 14:27:32

标签: java events listener

我正在尝试用Java创建自定义事件和侦听器。我已经看过这些文章和问题了:

Create a custom event in Java

Java custom event handler and listeners

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指出的自定义类?

1 个答案:

答案 0 :(得分:2)

所以我做了一个最小的例子,也许会帮助你:

您需要为听众提供一个界面:

public interface MyEventListener
{
    public void onMyEvent();
}

然后,对于你的String,你需要一个也处理事件的包装类

public class EventString
{
    private String                  myString;

    private List<MyEventListener>   eventListeners;

    public EventString(String myString)
    {
        this.myString = myString;
        this.eventListeners = new ArrayList<MyEventListener>();
    }

    public void addMyEventListener(MyEventListener evtListener)
    {
        this.eventListeners.add(evtListener);
    }

    public void setValue(String val)
    {
        myString = val;

        if (val.equals("hello world"))
        {
            eventListeners.forEach((el) -> el.onMyEvent());
        }
    }
}

您会看到myString字段是私有的,只能使用setValue方法访问。这是我们可以看到我们的事件条件何时触发。

然后你只需要实现一些,例如:

EventString temp = new EventString("test");

temp.addMyEventListener(() -> {
    System.out.println("hello world detected");
});

temp.setValue("hello world");