Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate Class class for a primitive type?

Tags:

java

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") == int.class; // exception here

How should I do this properly?

like image 463
yegor256 Avatar asked Feb 17 '11 18:02

yegor256


People also ask

Can primitive types be instantiated?

Can array of primitive data type be instantiated? Yes.

Can a class be used for a primitive type?

A Wrapper class in Java is used to convert a primitive data type to an object and object to a primitive type. Even the primitive data types are used for storing primary data types, data structures such as Array Lists and Vectors store objects.

How do you instantiate a class in Java?

Instantiating a ClassThe new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The new operator returns a reference to the object it created.

Can we create object of primitive data type in Java?

Simply No, You can not create primitive datatype.


1 Answers

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.

like image 151
Bozho Avatar answered Sep 21 '22 17:09

Bozho