【问题标题】:Java - Create a Custom event and listenerJava - 创建自定义事件和侦听器
【发布时间】:2018-08-28 03:41:33
【问题描述】:

我正在尝试用 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 指出的自定义类?

【问题讨论】:

  • 不能给String添加方法,可以添加到自己使用的类中
  • 您可以使用 Kotlin 及其扩展来做到这一点。一个包装类和一个关于事件的 Java 101 教程应该在 Java 中完成。
  • 您可以创建自己的类EventString(或其他),在其中有一个字符串对象,然后为它实现一个自定义事件监听器。
  • @Ben 我如何实现自定义事件监听器?正如我所说,在阅读了多个问题和文章后我仍然不太了解它
  • 基本上,事件监听器并不神奇。为了让侦听器工作,您需要编写一种机制,在发生更改时触发事件。也就是说,您不能让程序直接分配给字符串 - 您必须通过该机制来完成。

标签: java events listener


【解决方案1】:

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

你需要一个监听器接口:

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");

【讨论】:

  • 有没有一种方法可以在您拨打setValue 时不检查,而是不断检查?也许有一个while循环?
  • 您可以随时触发事件。只需使用eventListeners.forEach((el) -&gt; el.onMyEvent()); 行。
猜你喜欢
  • 2016-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
  • 2012-09-28
  • 2013-03-08
相关资源
最近更新 更多