Search code examples
javaboxing

Method to box primitive type


Here is a table of primitive types and their equivalent wrapper class.

Primitive type  Wrapper class
==============  =============
 boolean        Boolean
 byte           Byte
 char           Character
 float          Float
 int            Integer
 long           Long
 short          Short
 double         Double

I would like to create a method that would convert any given primitive variable into an appropriate class. I have tried something like below, but that obviously does not work. Any help would be appreciated:

public static <T> T forceBox(T t) {
  switch (T) {
    case boolean.class : return new Boolean(t);
    case int.class     : return new Integer(t);
    // etc
  }
}

the caller code looks like:

int x = 3;
System.out.println("x wrapper type: " + forceBox(x).getClass());

Solution

  • Though this is completely unnecessary in most cases, just use

    public static <T> T forceBox(T t) { // compiler will add the conversion at the call site
        return t; 
    }
    

    Though you can also just use

    Object o = <some primitive>;