How to cast an Object to an int

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

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

相关标签:
19条回答
  • 2020-11-27 10:09

    I guess you're wondering why C or C++ lets you manipulate an object pointer like a number, but you can't manipulate an object reference in Java the same way.

    Object references in Java aren't like pointers in C or C++... Pointers basically are integers and you can manipulate them like any other int. References are intentionally a more concrete abstraction and cannot be manipulated the way pointers can.

    0 讨论(0)
  • 2020-11-27 10:14

    Answer:

    int i = ( Integer ) yourObject;
    

    If, your object is an integer already, it will run smoothly. ie:

    Object yourObject = 1;
    //  cast here
    

    or

    Object yourObject = new Integer(1);
    //  cast here
    

    etc.

    If your object is anything else, you would need to convert it ( if possible ) to an int first:

    String s = "1";
    Object yourObject = Integer.parseInt(s);
    //  cast here
    

    Or

    String s = "1";
    Object yourObject = Integer.valueOf( s );
    //  cast here
    
    0 讨论(0)
  • 2020-11-27 10:14

    Refer This code:

    public class sample 
    {
      public static void main(String[] args) 
      {
        Object obj=new Object();
        int a=10,b=0;
        obj=a;
        b=(int)obj;
    
        System.out.println("Object="+obj+"\nB="+b);
      }
    }
    
    0 讨论(0)
  • 2020-11-27 10:17

    Can't be done. An int is not an object, it's a primitive type. You can cast it to Integer, then get the int.

     Integer i = (Integer) o; // throws ClassCastException if o.getClass() != Integer.class
    
     int num = i; //Java 1.5 or higher
    
    0 讨论(0)
  • 2020-11-27 10:19

    Assuming the object is an Integer object, then you can do this:

    int i = ((Integer) obj).intValue();
    

    If the object isn't an Integer object, then you have to detect the type and convert it based on its type.

    0 讨论(0)
  • 2020-11-27 10:19

    For Example Object variable; hastaId

    Object hastaId = session.getAttribute("hastaID");
    

    For Example Cast an Object to an int,hastaID

    int hastaID=Integer.parseInt(String.valueOf(hastaId));
    
    0 讨论(0)
提交回复
热议问题