[ACCEPTED]-How to instantiate Class class for a primitive type?-java

Accepted answer
Score: 17

You can't, because primitives are not objects.

What 17 you are trying currently though is not yet 16 instantiation - it is loading a class. But 15 you can't do that for primitives. int is indeed 14 the name that is used for int types, whenever 13 their Class object is obtained (via reflection, for 12 example method.getReturnType()), but you can't load it with forName().

Reference: Reflection tutorial:

If 11 the fully-qualified name of a class is available, it 10 is possible to get the corresponding Class 9 using the static method Class.forName(). This cannot be used for primitive types

A 8 solution to instantiate a primitive is to 7 use commons-lang ClassUtils, which can get the wrapper class corresponding 6 to a given primitive:

if (clazz.isPrimitive() {
    clazz = ClassUtils.primitiveToWrapper(clazz);
}
clazz.newInstance();

Note that this assumes 5 you have the Class representing the int type 4 - either via reflection, or via the literal 3 (int.class). But it is beyond me what would be the 2 usecase of having a string representation 1 of that. You can use forName("java.lang.Integer") instead.

Score: 7

We use or own simple method (Java 7+):

/**
 * Return the java {@link java.lang.Class} object with the specified class name.
 *
 * This is an "extended" {@link java.lang.Class#forName(java.lang.String) } operation.
 *
 * + It is able to return Class objects for primitive types
 * + Classes in name space `java.lang` do not need the fully qualified name
 * + It does not throw a checked Exception
 *
 * @param className The class name, never `null`
 *
 * @throws IllegalArgumentException if no class can be loaded
 */
public static Class<?> parseType(final String className) {
    switch (className) {
        case "boolean":
            return boolean.class;
        case "byte":
            return byte.class;
        case "short":
            return short.class;
        case "int":
            return int.class;
        case "long":
            return long.class;
        case "float":
            return float.class;
        case "double":
            return double.class;
        case "char":
            return char.class;
        case "void":
            return void.class;
        default:
            String fqn = className.contains(".") ? className : "java.lang.".concat(className);
            try {
                return Class.forName(fqn);
            } catch (ClassNotFoundException ex) {
                throw new IllegalArgumentException("Class not found: " + fqn);
            }
    }
}

0

Score: 4

Try ApacheCommons ClassUtils like this:

ClassUtils.getClass(className)

Works 2 for primitives nicely.

The full name for 1 the class is org.apache.commons.lang3.ClassUtils

Score: 2

In this case, the best you can hope for 3 is to create a map of primitives to their 2 Autoboxed equivalent and return a class 1 of that type.

More Related questions