title: Dynamic casting in Java
body: <p>Before I get chided for not doing my homework, I've been unable to find any clues on the multitude of questions on Java generics and dynamic casting.</p>
  
  <p>The type Scalar is defined as follows:</p>
  
  <pre><code>public class Scalar &lt;T extends Number&gt; {
  
    public final String name;
  
    T value;
  
    ... 
  
    public T getValue() {
      return value;
    }
  
    public void setValue(T val) {
      this.value = val;      
    }
  
  }
  </code></pre>
  
  <p>I would like to have a method that looks like this:</p>
  
  <pre><code>public void evilSetter(V val) {
    this.value = (T) val;
  }
  </code></pre>
  
  <p>Sure, this is generally discouraged. The reason I want such a method is because I have a collection of Scalars whose values I'd like to change later. However, once they go in the collection, their generic type parameters are no longer accessible. So even if I want make an assignment that's perfectly valid at runtime, there's no way of knowing that it'll be valid at compile time, with or without generics.</p>
  
  <pre><code>Map&lt;String, Scalar&lt;? extends Number&gt;&gt; scalars = ...;
  
  Scalar&lt;? extends Number&gt; scalar = scalars.get("someId");
  
  // None of this can work
  scalar.value = ...
  scalar.setValue(...)
  </code></pre>
  
  <p>So how do I implement a checked cast and set method? </p>
  
  <pre><code>public &lt;V extends Number&gt; void castAndSet(V val) {
      // One possibility
      if (this.value.getClass().isAssignableFrom(val.getClass()) {
         // Some cast code here
      }
      // Another
      if (this.value.getClass().isInstanceOf(val) {
         // Some cast code here    
      }
      // What should the cast line be?
      // It can't be:
      this.value = this.value.getClass().cast(val);
      // Because this.value.getClass() is of type Class&lt;?&gt;, not Class&lt;T&gt;        
  
  }
  </code></pre>
  
  <p>So I'm left with using </p>
  
  <pre><code>this.value = (T) val;
  </code></pre>
  
  <p>and catching a ClassCastException?</p>