Converting Integer to Long
Asked Answered
F

17

142

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 I have created the following method:

@SuppressWarnings("unchecked")
private static <T> T getValueByReflection(VarInfo var, Class<?> classUnderTest, Object runtimeInstance) throws Throwable {
  Field f = classUnderTest.getDeclaredField(processFieldName(var));
  f.setAccessible(true);
  T value = (T) f.get(runtimeInstance);

  return value;
}

And use this method like:

Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);

or

Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance);

The problem is that I can't seem to cast Integer to Long:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

Is there a better way to achieve this?

I am using Java 1.6.

Fuliginous answered 14/7, 2011 at 8:57 Comment(0)
S
108

No, you can't cast Integer to Long, even though you can convert from int to long. For an individual value which is known to be a number and you want to get the long value, you could use:

Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp.longValue();

For arrays, it will be trickier...

Southeasterly answered 14/7, 2011 at 8:59 Comment(5)
For arrays I can use a Number[] and a loop over it to create an appropriately typed array, right?Fuliginous
@Tiago: It depends on what the method's actually returning. That wouldn't work for a double[] for example, but would work for a Double[].Southeasterly
Why can't you cast from an Integer to a Long?Abdulabdulla
@MrMas: Because they're separate reference types, both direct subclasses of Number. Or to put it another way: which conversion rule do you believe does let you convert from one to the other?Southeasterly
Ok. The problem is inheritance. I'm thinking in terms of precision. An integer can be converted to a long integer without losing information. But the inheritance structure doesn't have any information that would tell the compiler that.Abdulabdulla
L
158

Simply:

Integer i = 7;
Long l = new Long(i);
Lyublin answered 11/9, 2013 at 9:38 Comment(5)
NPE is thrown if the Integer is nullUnpremeditated
Works for int values.Retrorse
Long.valueof should be used: https://mcmap.net/q/160531/-new-integer-vs-valueofFrancis
This code works (Java implicitly unboxes the Integer to int and then casts to long before passing to the now deprecated Long(long) constructor.Ontina
new Long is deprecatedTryma
S
108

No, you can't cast Integer to Long, even though you can convert from int to long. For an individual value which is known to be a number and you want to get the long value, you could use:

Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp.longValue();

For arrays, it will be trickier...

Southeasterly answered 14/7, 2011 at 8:59 Comment(5)
For arrays I can use a Number[] and a loop over it to create an appropriately typed array, right?Fuliginous
@Tiago: It depends on what the method's actually returning. That wouldn't work for a double[] for example, but would work for a Double[].Southeasterly
Why can't you cast from an Integer to a Long?Abdulabdulla
@MrMas: Because they're separate reference types, both direct subclasses of Number. Or to put it another way: which conversion rule do you believe does let you convert from one to the other?Southeasterly
Ok. The problem is inheritance. I'm thinking in terms of precision. An integer can be converted to a long integer without losing information. But the inheritance structure doesn't have any information that would tell the compiler that.Abdulabdulla
M
76
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.

Minor answered 9/8, 2013 at 15:34 Comment(1)
To be null save: Long l = i == null ? null : i.longValue()Saline
P
21

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.

Pareira answered 26/7, 2012 at 2:50 Comment(5)
It makes absolutely no sense for me, but it works like a charm. Thanks a lot!Epicycloid
Introducing a string conversion for no reason is a really bad idea... there's simply no benefit in doing this.Southeasterly
Agree with @JonSkeet, better off with this:Object i = 10;Long l = ((Number) i).longValue();Estren
This method works fine but is relatively slow and uses more memory than the other methods of doing this...Acicular
looks great from a front end developer perspectiveUntitled
P
13

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.

Pumice answered 4/7, 2017 at 6:33 Comment(2)
I can't find a Long.valueOf(Integer i) method, the only ones I find are valueOf(long l), valueOf(String s) and valueOf(String s, int radix). Checked for Java8 and Java9 docs.Allinclusive
Integer is implicitly converted to a primitive long type.Pumice
T
10

Converting Integer to Long Very Simple and many ways to converting that
Example 1

 new Long(your_integer);

Example 2

Long.valueOf(your_integer); 

Example 3

Long a = 12345L;

Example 4
If you already have the int typed as an Integer you can do this:

Integer y = 12;
long x = y.longValue();
Thiamine answered 28/4, 2016 at 10:21 Comment(0)
D
6

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

Long i = 1234L;
Dermal answered 17/4, 2015 at 7:9 Comment(3)
I am sure you have answered without reading the entire question!Filtration
@Filtration this question is the first result when searching "int to long" on Google, this answer may be useful to othersCutin
@DimitriW I am not saying this answer is wrong, But I am saying the answer for this question is wrong. You are right,This is useful for those people who doesn't read the question and look at the answer only.Filtration
L
5
((Number) intOrLongOrSomewhat).longValue()
Lubber answered 2/8, 2016 at 18:15 Comment(0)
S
2

If you know that the Integer is not NULL, you can simply do this:

Integer intVal = 1;
Long longVal = (long) (int) intVal
Snath answered 10/6, 2016 at 14:50 Comment(0)
D
2
new Long(Integer.longValue());

or

new Long(Integer.toString());
Dhahran answered 15/6, 2016 at 12:38 Comment(0)
I
2

If you don't know the exact class of your number (Integer, Long, Double, whatever), you can cast to Number and get your long value from it:

Object num = new Integer(6);
Long longValue = ((Number) num).longValue();
Icky answered 28/7, 2020 at 9:31 Comment(0)
Y
1

A parser from int variables to the long type is included in the Integer class. Here is an example:

int n=10;
long n_long=Integer.toUnsignedLong(n);

You can easily use this in-built function to create a method that parses from int to long:

    public static long toLong(int i){
    long l;
    if (i<0){
        l=-Integer.toUnsignedLong(Math.abs(i));
    }
    else{
        l=Integer.toUnsignedLong(i);
    }
    return l;
}
Yseulta answered 29/3, 2017 at 15:48 Comment(0)
E
1

For a nullable wrapper instance,

Integer i;
Long l = Optional.ofNullable(i)
                 .map(Long::valueOf)
                 .orElse(null);
Epos answered 30/3, 2021 at 3:28 Comment(0)
K
1

To convert Integer into Long simply cast the Integer value

Integer intValue = 23;
Long longValue = (long) intValue;
Kirbie answered 11/12, 2021 at 14:36 Comment(0)
O
0

This is null-safe

Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp == null ? null : tmp.longValue();
Octoroon answered 25/9, 2018 at 7:30 Comment(0)
C
-3

In case of a List of type Long, Adding L to end of each Integer value

List<Long> list = new ArrayList<Long>();
list  = Arrays.asList(1L, 2L, 3L, 4L);
Carlicarlick answered 8/1, 2018 at 9:52 Comment(0)
A
-4

Try to convertValue by Jackson

ObjectMapper mapper = new ObjectMapper()
Integer a = 1;
Long b = mapper.convertValue(a, Long.class)
Asthenosphere answered 31/1, 2020 at 15:17 Comment(1)
This is definitely not the best answer: this solution adds unnecessary complexity, performance overhead and requires an extra library (Jackson)Reviere

© 2022 - 2024 — McMap. All rights reserved.