Converting Integer to Long

前端 未结 16 2037
轮回少年
轮回少年 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:08

    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...

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

    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;
    }
    
    0 讨论(0)
  • 2020-12-07 14:12

    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();
    
    0 讨论(0)
  • 2020-12-07 14:13

    Simply:

    Integer i = 7;
    Long l = new Long(i);
    
    0 讨论(0)
  • 2020-12-07 14:15

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

    Integer intVal = 1;
    Long longVal = (long) (int) intVal
    
    0 讨论(0)
  • 2020-12-07 14:17
    ((Number) intOrLongOrSomewhat).longValue()
    
    0 讨论(0)
提交回复
热议问题