Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There will not be any ClassCastException, except when your T has some base:</p> <pre><code>public class GenericsTest { public static void main(String[] args) { System.out.println(cast(Integer.valueOf(0))); System.out.println(GenericsTest.&lt;Long&gt; cast(Integer.valueOf(0))); System.out.println(GenericsTest.&lt;Long&gt; cast("Hallo")); System.out.println(castBaseNumber(Integer.valueOf(0))); System.out.println(GenericsTest.&lt;Long&gt; castBaseNumber(Integer.valueOf(0))); System.out.println(GenericsTest.&lt;Long&gt; castBaseNumber("Hallo")); } private static &lt;T extends Number&gt; T castBaseNumber(Object o) { T t = (T)o; return t; } private static &lt;T&gt; T cast(Object o) { T t = (T)o; return t; } } </code></pre> <p>In the above example, there will be no ClassCastException in the first 5 calls to cast and castBaseNumber. Only the 6th call throws a ClassCastException, because the compiler effectively translates the cast() to return (Object) o and the castBaseNumber() to return (Number)o;. Wenn you write</p> <pre><code>String s = GenericsTest.&lt;Long&gt; cast("Hallo"); </code></pre> <p>You would get a ClassCastException, but not whithin the cast-method, but at the assignment to s.</p> <p>Therefore I do think, your "T" is not just "T", but "T extends Something". So you could check:</p> <pre><code>Object o = decoder.readObject(); if (o instanceof Something) restoredItem = (T) o; else // Error handling </code></pre> <p>But this will still lead to an error later, when the you use your class.</p> <pre><code>public Reader&lt;T extends Number&gt;{...} Long l = new Reader&lt;Long&gt;("file.xml").getValue(); // there might be the ClassCastException </code></pre> <p>For this case only Tom's advise might help.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload