I'm trying to get hang of custom events and listeners. I found example of single event-listener, but I'm curious how to extend from single method to multiple that are related.
public interface CountListener{
public void countEvent(int count);
public void multiplyEvent(int multi);
}
public class Counter implements CountListener{
public void countEvent(int count){
System.out.println("Counter: "+count);
}
public void multiplyEvent(int multi){
System.out.println("Multiply: " +multi*multi);
}
}
import java.util.*;
import java.lang.reflect.Method;
public class CountTest {
ArrayList listeners;
public void addCountListener(CountListener c){
listeners.add(c);
}
public void removeCountListener(CountListener c){
if(listeners.contains(c)){
listeners.remove(listeners.indexOf(c));
}
}
public void fireEvent(int count, Object methodObj){
Iterator i = listeners.iterator();
while(i.hasNext()){
//((CountListener)i.next()).countEvent(count);
Object obj = i.next();
System.out.println(obj.getClass().getName());
Method[] meth = obj.getClass().getDeclaredMethods();
for(Method m : meth){
if(m.equals(methodObj)){
System.out.println(m.getName());
try{
m.invoke(methodObj, count);
}
catch(Exception e){
}
}
}
}
}
public CountTest(){
listeners = new ArrayList();
}
public void count(int i){
fireEvent(i, (Object) "countEvent");
}
public void multiply(int i){
fireEvent(i, (Object) "multiplyEvent");
}
public static void main(String[] args){
CountTest c = new CountTest();
c.addCountListener(new Counter());
/*for(int i = 0; i < 10; i++){
c.count(i);
}*/
c.count(5);
c.multiply(5);
}
}
As you can see from above example I'm able to break down class on all methods provided by this class. However I'm not bale to call appropriate method that much my listener call. fireEvent(i, (Object) "countEvent");
is just blatant attempt because I know compile will not fire errors. So question is how do I declare this Object so it will work? Or am I completely of the hock with my attempt?