Using primitive types with ClassLoader

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?

+5
source share
2 answers

Since you have an exception for this: Class.forName(int.class.getName())I would say that this is the way to go.

Spring http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/util/ClassUtils.html class, method resolvePrimitiveClassName, , , ;). : 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%29

- :

private static final Map primitiveTypeNameMap = new HashMap(16);
// and populate like this
primitiveTypeNames.addAll(Arrays.asList(new Class[] {
        boolean[].class, byte[].class, char[].class, double[].class,
        float[].class, int[].class, long[].class, short[].class}));
for (Iterator it = primitiveTypeNames.iterator(); it.hasNext();) {
    Class primitiveClass = (Class) it.next();
    primitiveTypeNameMap.put(primitiveClass.getName(), primitiveClass);
}
+3

, . :

private Pattern arrayPattern = Pattern.compile("([\\w\\.]*)\\[\\]");

public Class<?> getClassFor(String className) throws ClassNotFoundException {
    Matcher m = arrayPattern.matcher(className);
    if(m.find()) {
        String elementName = m.group(1);
        return Class.forName("[L" + elementName + ";"); // see below
    }
    return Class.forName(className);
}

[L ( ); - . , , .

, ...

0

All Articles