-1

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());
MaxZoom
  • 7,619
  • 5
  • 28
  • 44

2 Answers2

2

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>;
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

The conversion is already done when needed as part of the boxing process.

MaxZoom
  • 7,619
  • 5
  • 28
  • 44
Tunaki
  • 132,869
  • 46
  • 340
  • 423