How to instantiate Class class for a primitive type?

前端 未结 4 2134
谎友^
谎友^ 2021-01-01 17:19

I\'m trying to do this, but doesn\'t work:

public static Class loadIt(String name) throws Throwable {
  return Class.forName(name);
}
assert foo.loadIt(\"int         


        
4条回答
  •  失恋的感觉
    2021-01-01 17:29

    You can't, because primitives are not objects.

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

    Reference: Reflection tutorial:

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

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

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

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

提交回复
热议问题