Dynamically find the class that represents a primitive Java type

The Spring framework contains a utility class ClassUtils which contains the static method forName. This method can be used for the exact purpose you described.

In case you don’t like to have a dependency on Spring: the source code of the method can be found e. g. here on their public repository. The class source code is licensed under the Apache 2.0 model.

Note however that the algorithm uses a hard-coded map of primitive types.


Edit: Thanks to commenters Dávid Horváth and Patrick for pointing out the broken link.


The Class instances for the primitive types are obtainable as you said using e.g. int.class, but it is also possible to get the same values using something like Integer.TYPE. Each primitive wrapper class contains a static field, TYPE, which has the corresponding primitive class instance.

You cannot obtain the primitive class via forName, but you can get it from a class which is readily available. If you absolutely must use reflection, you can try something like this:

Class clazz = Class.forName("java.lang.Integer");
Class intClass = clazz.getField("TYPE").get(null);

intClass.equals(int.class);         // => true