title: Avoiding 'instanceof' in Java
body: <p>I have the following (maybe common) problem and it absolutely puzzles me at the moment:</p>
  
  <p>There are a couple of generated event objects which extends the abstract class <code>Event</code> and I want to divide them to Session Beans, like</p>
  
  <pre><code>public void divideEvent(Event event) {
      if (event instanceof DocumentEvent) {
          documentGenerator.gerenateDocument(event);
      } else if (event instanceof MailEvent) {
          deliveryManager.deliverMail(event);
          ...
      }
      ...
  
  }
  </code></pre>
  
  <p>But there could be more than two event types in future, so the if-else will be long and maybe unreadable. Additionally I think <code>instanceof</code> is not really "best practice" in this case.</p>
  
  <p>I could add an abstract method to the <code>Event</code> type and have them divide itself but then I have to inject the specific Session Beans within each entity.</p>
  
  <p>Is there any hint to achieve a "pretty" solution for this problem?</p>
  
  <p>Thanks for any help!</p>