title: Event source: Short way to fire event
body: <p>I'm writing Event Source template for my classes:</p>
  
  <pre><code>public class EventSource&lt;E&gt; {
    protected ArrayList&lt;E&gt; listeners = new ArrayList&lt;E&gt;();
  
    public void addListener(E listener)
    {
      listeners.add(listener);
    }
  
    public void removeListener(E listener)
    {
      listeners.remove(listener);
    }
  }
  </code></pre>
  
  <p>To fire an event I need to call something like:</p>
  
  <pre><code>for(SomeListener listener: listeners)
    listener.onSomeEvent();
  </code></pre>
  
  <p>This looks quite ugly to fire an event. Is there a way to call something shorter like:</p>
  
  <pre><code>fire(SomeListener.onSomeEvent)
  </code></pre>
  
  <p>or</p>
  
  <pre><code>fire(onSomeEvent)
  </code></pre>
  
  <p>?</p>
  
  <p>I've already found 3 solutions:</p>
  
  <p>I Use java reflections and pass method name as argument to some method in template, which will call this method for all the listeners. But I think it is inefficient because of needed parsing the string (method name). And how to pass parameters in not the ugly way - question remains.</p>
  
  <p>II Use the same name for all the methods, but pass different parameter:</p>
  
  <pre><code>public struct SomeEvent1
  {
    int someData;
  }
  
  public struct SomeEvent2
  {
    int someAnotherData;
    double probablyMoreData;
  }
  
  public interface SomeListener
  {
    public void fire(SomeEvent1 e);
    public void fire(SomeEvent2 e);
  }
  </code></pre>
  
  <p>But it requires building this event structs even if I don't need any parameters.</p>
  
  <p>III Using delegation. Imagine, that SomeEventSource extends EventSource. Now I can call onSomeEventI(), because I've written those methods in SomeEventSource:</p>
  
  <pre><code>public void onSomeEventI()
  {
    for(SomeListener listener: listeners)
      listener.onSomeEventI();
  }
  </code></pre>
  
  <p>But I can't write those methods in generic EventSource, because it is Listener-agnostic. And writing those methods in SomeEventSource makes generic EventSource more useless, than usefull.</p>
  
  <p>The question remains: how to fire an event in the short way?</p>