Simple way to get wrapper class type in Java

I have a piece of code where I need to pass the class of a field in a method. Because of the mechanics of my code I can only handle reference objects and not primitives. I want an easy way of determining if a Field's type is primitive and swap it with the appropriate wrapper class. So in code what I do so far is something like this:

Field f = getTheField(); // Dummy method that returns my Field
Class<?> c = f.getType();
if (c == int.class) {
    c = Integer.class;
else if (c == float.class) {
    c = Float.class;
// etc

This works fine, except for the fact that I need to explicitly check for all the primitive types and swap them with the appropriate wrapper class. Now I know that there are not so many primitive types and it won't be a problem to simply list them all, but I was wondering if there was an easier and more elegant way of doing it.


  • I think this answer is probably the right way now

    Or, Guava has this:

    It has the wrap() method, plus unwrap() and a few other incidental things.

    If you don't use Guava, you can follow the example of its implementation.