1
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.

Aequitas
  • 2,205
  • 1
  • 25
  • 51
  • 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. – user2864740 Sep 03 '15 at 05:51
  • in your comments you always ask for the name of the class - maybe you're looking for `java.lang.Class.getName()` ?? – Martin Frank Sep 03 '15 at 05:52
  • Start by using [`Class#isAssignableFrom`](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#isAssignableFrom-java.lang.Class-) 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. – MadProgrammer Sep 03 '15 at 06:03
  • Then use something like [`Class#getConstructor(Class...)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getConstructor-java.lang.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);` – MadProgrammer Sep 03 '15 at 06: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. – Louis Wasserman Sep 03 '15 at 06:38

3 Answers3

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)
Naman Gala
  • 4,670
  • 1
  • 21
  • 55
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.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • Just curious, what does this have to do with the class being `immutable`? – Codebender Sep 03 '15 at 05:53
  • 1
    `co[1]`? Hope all versions of Java has the same constructors in the same sequence. – Andreas Sep 03 '15 at 05:54
  • Integer *objects* are immutable; but such is not relevant to the question. – user2864740 Sep 03 '15 at 05:54
  • @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 Sep 03 '15 at 05:57
  • 1
    @TheLostMind `Integer` has **2** public constructors. – Andreas Sep 03 '15 at 05:58
  • @Andreas - My bad. I meant *default* constructor – TheLostMind Sep 03 '15 at 05:58
  • @TheLostMind Counter-argument: the default constructor could have initialized to the default/corresponding primitive value. And indeed, this is what happens in C# for the 'equivalent' type where the following is valid and true: `0 == new int()`. – user2864740 Sep 03 '15 at 05:59
  • @Andreas - I was just showing how this could be done. You are right. I should not have used `co[1]` – TheLostMind Sep 03 '15 at 05:59
  • @user2864740 - I believe this was done to ensure immutabililty and prevent other classes from extending `Integer` (I know `Integer` is `final`, but by convention classes which should not be extended have either no default constructor or a private one). I actually think java has done a good thing by ensuring that value is not initialized to `0` – TheLostMind Sep 03 '15 at 06:13
  • @TheLostMind Again, immutable is *completely unrelated* to not having a default constructor, as I demonstrated. The `int` type in C# is not mutable either. While we can argue if it is 'good' that it doesn't have a default constructor, being of an immutable value does not *prevent* a default constructor. – user2864740 Sep 03 '15 at 06:15
  • @user2864740 - What do you suggest?. Keep it there and make it private? – TheLostMind Sep 03 '15 at 06:16
  • @user2864740 - I know immutability does not have to do anything with default constructor (`String` has a public default constructor). I am merely trying to say that the designers of Java did not think that this was a good idea in wrapper classes – TheLostMind Sep 03 '15 at 06:19
-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
Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
  • 4
    `java.lang.InstantiationException ... Caused by: java.lang.NoSuchMethodException: java.lang.Integer.()` – MadProgrammer Sep 03 '15 at 05:49
  • 1
    Put back what you edited please, this answer actually helped me, thankyou – Aequitas Sep 03 '15 at 05:58
  • 1
    For upvoter: `Integer` class has no default constructor, so current code will raise an exception (noted by @MadProgrammer). – Luiggi Mendoza Sep 03 '15 at 05:58
  • @LuiggiMendoza but works if there is a default constructor so will work in lots of cases. – Aequitas Sep 03 '15 at 06:00
  • 1
    @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. – Luiggi Mendoza Sep 03 '15 at 06:01
  • @Aequitas I have changed littile bit code – Subodh Joshi Sep 03 '15 at 06:11
  • @LuiggiMendoza ah yes this is a subset of that question, since the first step there is getting the Class which I already have, then I just follow the next two steps like in this answer. – Aequitas Sep 03 '15 at 06:14
  • 1
    @Aequitas You seriously don't help the community... – Luiggi Mendoza Sep 03 '15 at 06:15
  • 1
    @LuiggiMendoza What did I do wrong? I searched for the answer to my question before posting it, I didn't come across that other question because it's asking given a class name string, whereas I was searching for given a Class. I'm sorry that I didn't find the duplicate before I asked, I also asked in the chat before I posted it to see if anyone could help. – Aequitas Sep 03 '15 at 08:07