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