I am trying to make a custom event and listener in Java. I already looked at these articles and questions:
Java custom event handler and listeners
https://www.javaworld.com/article/2077333/core-java/mr-happy-object-teaches-custom-events.html
But I still can't really wrap my head around it. This is what I want done:
I have a String
object whose content changes as the program runs. I want to be able to add a listener to the string which listens wether it contains a specific string and when it does run a piece of code. I want to use it like this:
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"
I know there might be easier ways of doing this, but I would like to know how to do it this way.
Thank you @Marcos Vasconcelos for pointing out that you cannot add methods to a String
object, so is there a way I can use a custom class like @Ben pointed out?