Search code examples
javajunitautoboxing

Difference between long.Class and Long.TYPE


Do they both return the same thing i.e Long Class. Actually i was using this within PrivilegedAccessor to pass as following

PrivilegedAccessor.invokeMethod(MyClass,
                "MyMethod", new Object[] { arg1, arg2 },
                new Class[] { long.class, Date.class });

Alternatively I can use

PrivilegedAccessor.invokeMethod(MyClass,
                    "MyMethod", new Object[] { arg1, arg2 },
                    new Class[] { Long.TYPE, Date.class });

Which is better to be used keeping in mind autoboxing / unboxing overheads.

** I am passing primitive long from the Test and even the tested method expects primitive long only.


Solution

  • They both represent the long primitive type. They are exactly the same, even in the compiled bytecode. Sample program:

    public class Main
    {
       public static void main(String[] args) {
          Class<Long> c = Long.TYPE;
          Class<Long> c1 = long.class;
       }
    }
    

    Then, using javap -c Main:

    c:\dev\src\misc>javap -c Main
    Compiled from "Main.java"
    public class Main {
      public Main();
        Code:
           0: aload_0
           1: invokespecial #1                  // Method java/lang/Object."<init>":
    ()V
           4: return
    
      public static void main(java.lang.String[]);
        Code:
           0: getstatic     #2                  // Field java/lang/Long.TYPE:Ljava/lang/Class;
           3: astore_1
           4: getstatic     #2                  // Field java/lang/Long.TYPE:Ljava/lang/Class;
           7: astore_2
           8: return
    }