I have a piece of code that is used to convert string representations that are delivered Class.getCanonicalName()to their respective instances Class. This can usually be done with ClassLoader.loadClass("className"). However, he fails on primitive types by throwing 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);
}
This seems very nasty to me, so is there any clean approach for this?
source
share