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
Try to convertValue by Jackson
ObjectMapper mapper = new ObjectMapper()
Integer a = 1;
Long b = mapper.convertValue(a, Long.class)
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.
Use the following: Long.valueOf(int);
or (Long) int ;
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.
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.
Convert an integer directly to long by adding 'L' to the end of Integer.
Long i = 1234L;