How to cast an Object to an int

后端 未结 19 2080
长情又很酷
长情又很酷 2020-11-27 09:58

How can I cast an Object to an int in java?

19条回答
  •  误落风尘
    2020-11-27 10:22

    If you're sure that this object is an Integer :

    int i = (Integer) object;
    

    Or, starting from Java 7, you can equivalently write:

    int i = (int) object;
    

    Beware, it can throw a ClassCastException if your object isn't an Integer and a NullPointerException if your object is null.

    This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.

    int is a primitive so it can't be stored as an Object, the only way is to have an int considered/boxed as an Integer then stored as an Object.


    If your object is a String, then you can use the Integer.valueOf() method to convert it into a simple int :

    int i = Integer.valueOf((String) object);
    

    It can throw a NumberFormatException if your object isn't really a String with an integer as content.


    Resources :

    • Oracle.com - Autoboxing
    • Oracle.com - Primitive Data types

    On the same topic :

    • Java: What's the difference between autoboxing and casting?
    • Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);
    • Convert Object into primitive int

提交回复
热议问题