|
New Instance
The following example shows how to create new instance in different ways.
|
package com.bethecoder.tutorials.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class NewInstance {
/**
* @param args
*/
public static void main(String[] args) {
String str = new String("Hello");
System.out.println("str : " + str);
try {
//Works if we have a public default constructor
//This is identical to creating instance
//using str = new String();
str = String.class.newInstance();
System.out.println("str : " + str);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
try {
//This is identical to creating instance
//using str = new String("World");
Constructor<String> stringConstructor = String.class.getConstructor(String.class);
str = stringConstructor.newInstance("World");
System.out.println("str : " + str);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
|
| |
It gives the following output,
str : Hello
str :
str : World
|
|