2
Class c = Integer.class

Say I only have c how can I create an Integer object from that?

Note that it doesn't necessarily need to be Integer, I'd like to do this for anything.

5
  • In response to a buried comment: Compile-time types are .. compile-time. It is not possible to declare a variable "of c" for an arbitrary Class object. You would have to treat the resulting object (however such is obtained) as the most generic covering type (eg. Object) and/or specialize-cast as required (eg. (Integer)i) and/or use reflection. Commented Sep 3, 2015 at 5:51
  • in your comments you always ask for the name of the class - maybe you're looking for java.lang.Class.getName() ?? Commented Sep 3, 2015 at 5:52
  • Start by using Class#isAssignableFrom to determine if the given Class can be assigned to a different class type, for example c.isAssignableFrom(Integer.class), this will, at least, tell you if the given class or compatible. Commented Sep 3, 2015 at 6:03
  • Then use something like Class#getConstructor(Class...), because Integer does not have a default constructor, something like c.getConstructor(int.class). Use the resulting Constructor to create a new instance of the class, something like Integer value = (Integer)con.newInstance(42); Commented Sep 3, 2015 at 6:04
  • @Aequitas what integer would you expect to get back? Most classes don't have a sensible default instance; what would you expect to get back for them? This doesn't make sense. Commented Sep 3, 2015 at 6:38

3 Answers 3

1

You can use newInstance() method.

c.newInstance();

Creates exception.

Output:

Caused by: java.lang.NoSuchMethodException: java.lang.Integer.<init>()

Update:

For the class who do not have default (no parameterized) constructor you can not create instance without knowing its type. For others see the below example and its output.

public static void main(String[] args) throws InstantiationException, IllegalAccessException {
    Class stringClass = String.class;
    Class integerClass = Integer.class;

    try {
        System.out.println(stringClass.getConstructor());
        Object obj = stringClass.newInstance();
        if (obj instanceof String) {
            System.out.println("String object created.");
        }

        System.out.println(integerClass.getConstructor());
        obj = integerClass.newInstance();
        if (obj instanceof Integer) {
            System.out.println("String object created.");
        }

    } catch (NoSuchMethodException e) {
        // You can not create instance as it does not have default constructor.
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

Output :

public java.lang.String()
String object created.
java.lang.NoSuchMethodException: java.lang.Integer.<init>()
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.getConstructor(Unknown Source)
    at xyz.Abc.main(Abc.java:15)
Sign up to request clarification or add additional context in comments.

5 Comments

how would I assign this to an object of Integer? like c.class integerObject = c.newInstance();
It will fail with an InstantiationException. The Integer class does not have a nullary constructor.
Caused by: java.lang.NoSuchMethodException: java.lang.Integer.<init>()
@RobbyCornelissen yes, you are right.
I have updated my answer.
0

Since instances of Integer class are immutable, you need to something like this :

public static void main(String args[]) throws Exception {
    Class<?> c = Integer.class;
    Constructor<?>[] co = c.getDeclaredConstructors(); // get Integer constructors
    System.out.println(Arrays.toString(co)); 
    Integer i = (Integer) co[1].newInstance("5"); //call one of those constructors.
    System.out.println(i);
}

O/P :

[public java.lang.Integer(int), public java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException]
5

You need to explicitly do these things because Integer class does not provide mutators / default constructor all we are initializing values by using constructor injection.

12 Comments

Just curious, what does this have to do with the class being immutable?
co[1]? Hope all versions of Java has the same constructors in the same sequence.
Integer objects are immutable; but such is not relevant to the question.
@user2864740 - It is. Since instances of Integer class are immutable, they don't have a default public constructor. So, you need to call another one explicitly
@TheLostMind Integer has 2 public constructors.
|
-2

Try this

Class c = Class.forName("package.SomeClass");//If you have any specific class 

And then instance :

Object obj = c.newInstance();

int intObj = (Integer) obj

9 Comments

java.lang.InstantiationException ... Caused by: java.lang.NoSuchMethodException: java.lang.Integer.<init>()
Put back what you edited please, this answer actually helped me, thankyou
For upvoter: Integer class has no default constructor, so current code will raise an exception (noted by @MadProgrammer).
@Aequitas your question is about Integer, and this doesn't respond that. Also, this is already covered in the duplicate Q/A, there's no need to repost it here.
@Aequitas You seriously don't help the community...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.