Converting Integer to Long

前端 未结 16 2038
轮回少年
轮回少年 2020-12-07 13:47

I need to get the value of a field using reflection. It so happens that I am not always sure what the datatype of the field is. For that, and to avoid some code duplication

相关标签:
16条回答
  • 2020-12-07 14:17

    Try to convertValue by Jackson

    ObjectMapper mapper = new ObjectMapper()
    Integer a = 1;
    Long b = mapper.convertValue(a, Long.class)
    
    0 讨论(0)
  • 2020-12-07 14:18

    Oddly enough I found that if you parse from a string it works.

     int i = 0;
     Long l = Long.parseLong(String.valueOf(i));
     int back = Integer.parseInt(String.valueOf(l));
    

    Win.

    0 讨论(0)
  • 2020-12-07 14:20

    Use the following: Long.valueOf(int);

    or (Long) int ;

    0 讨论(0)
  • 2020-12-07 14:21
    Integer i = 5; //example
    
    Long l = Long.valueOf(i.longValue());
    

    This avoids the performance hit of converting to a String. The longValue() method in Integer is just a cast of the int value. The Long.valueOf() method gives the vm a chance to use a cached value.

    0 讨论(0)
  • 2020-12-07 14:21

    If the Integer is not null

    Integer i;
    Long long = Long.valueOf(i);
    

    i will be automatically typecast to a long.

    Using valueOf instead of new allows caching of this value (if its small) by the compiler or JVM , resulting in faster code.

    0 讨论(0)
  • 2020-12-07 14:23

    Convert an integer directly to long by adding 'L' to the end of Integer.

    Long i = 1234L;
    
    0 讨论(0)
提交回复
热议问题