samedi 20 janvier 2018

Cannot cast java.lang.Integer to int [duplicate]

This question already has an answer here:

I'm confused by the following Java code, in which I try to use two methods to cast an Object to an int:

Object o = 1;
System.out.println((int) o);
Class <?> t = int.class;
System.out.println(t.cast(o));

The second line casts the Object to an int traditionally, and succeeds. The fourth, however, which I would expect to be functionally equivalent, throws

Exception in thread "main" java.lang.ClassCastException: Cannot cast java.lang.Integer to int

What's the functional difference between the second line and the fourth? Why would one fail while the other succeeds?





Aucun commentaire:

Enregistrer un commentaire