I’ve got a piece of code that is used to turn string representations delivered by Class.getCanonicalName() into their corresponding instances of Class. This usually can be done using ClassLoader.loadClass("className"). However, it fails on primitive types throwing a ClassNotFoundException. The only solution I came across was something like this:
private Class<?> stringToClass(String className) throws ClassNotFoundException {
if("int".equals(className)) {
return int.class;
} else if("short".equals(className)) {
return short.class;
} else if("long".equals(className)) {
return long.class;
} else if("float".equals(className)) {
return float.class;
} else if("double".equals(className)) {
return double.class;
} else if("boolean".equals(className)) {
return boolean.class;
}
return ClassLoader.getSystemClassLoader().loadClass(className);
}
That seems very nasty to me, so is there any clean approach for this?
Since you have an exception for this:
Class.forName(int.class.getName()), I would say this is the way to go.Checking Spring framework code http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/util/ClassUtils.html class, method
resolvePrimitiveClassName, you will see that they do the same thing, but with a map ;). Source code: http://grepcode.com/file/repository.springsource.com/org.springframework/org.springframework.core/3.1.0/org/springframework/util/ClassUtils.java#ClassUtils.resolvePrimitiveClassName%28java.lang.String%29Something like this: