title: Switch over type in java
body: <p>Before I start, I know there are a bunch of answers to this question that suggest alternate approaches.  I'm looking for assistance to this particular approach as to whether it is possible, and if not, similar approaches that might work.</p>
  
  <p>I have a method that takes a superclass and calls a method based on the type of the passed object.  for instance:</p>
  
  <pre><code>public void handle(Object o){
    if (o instanceof A)
      handleA((A)o);
    else if (o instanceof B)
      handleB((B)o);
    else if (o instanceof C)
      handleC((C)o);
    else 
      handleUnknown(o);
  </code></pre>
  
  <p>I can't modify the subtypes to override a <code>handle()</code> method, as <a href="https://stackoverflow.com/questions/5579309/switch-instanceof/5579385#5579385">this answer</a> would suggest, because I don't own the classes.  So the <code>instanceof</code> method is all I have.</p>
  
  <p>I'd like to use a <code>switch</code> statement instead of <code>if/else</code>, simply because it's much neater.  I know you can only switch on primitives and Strings, so I'm switching over the class name:</p>
  
  <pre><code>switch(o.getClass().getCanonicalName()){
  case "my.package.A":
    handleA((A)o);
    break;
  case "my.package.B":
    handleB((B)o);
    break;
  case "my.package.C":
    handleC((C)o);
    break;
  default:
    handleUnknown(o);
    break;
  }
  </code></pre>
  
  <p>The catch here is that the canonical names are VERY long (like 12 subpackages), and I can't call <code>ClassName.class.getCanonicalName()</code> in the case statement because Java doesn't allow that.  So my next solution was an Enum.  This is where I hit my problem.</p>
  
  <p>I'd like my code to look something like this:</p>
  
  <pre><code>public enum Classes {
    A (A.getCanonicalName()),
    B (B.getCanonicalName()),
    C (C.getCanonicalName());
  }
  
  switch (o.getClass().getCanonicalName()){
  case Classes.A:
    handleA((A)o);
    break;
  case Classes.B:
    handleB((B)o);
    break;
  case Classes.C:
    handleC((C)o);
    break;
  default:
    handleUnknown(o);
    break;
  }
  </code></pre>
  
  <p>But this doesn't compile.  I'm not sure why.  I'd like some approach that allows me to switch over the type without having to type out the entire canonical name.  If I do that, I might as well just use <code>if/else</code> and <code>instanceof</code>.</p>
  
  <p><strong>NOTE</strong> There are a couple of types that have the same name (inner classes), so <code>getSimpleName()</code> is out.</p>