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

Con*_*sen 3 java events listener

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

在 Java 中创建自定义事件

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"
Run Code Online (Sandbox Code Playgroud)

我知道可能有更简单的方法来做到这一点,但我想知道如何做到这一点。

谢谢@Marcos Vasconcelos 指出您不能向String对象添加方法,那么有没有办法使用@Ben 指出的自定义类?

Ben*_*Ben 6

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

您需要为您的听众提供一个接口:

public interface MyEventListener
{
    public void onMyEvent();
}
Run Code Online (Sandbox Code Playgroud)

然后对于你的 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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

EventString temp = new EventString("test");

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

temp.setValue("hello world");
Run Code Online (Sandbox Code Playgroud)