The example below using a constructor reflection to create a string object by calling String(String)
and String(StringBuilder)
constructors.
package org.kodejava.lang.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class CreateObjectDemo {
public static void main(String[] args) {
Class<String> clazz = String.class;
try {
Constructor<String> constructor = clazz.getConstructor(String.class);
String object = constructor.newInstance("Hello World!");
System.out.println("String = " + object);
constructor = clazz.getConstructor(StringBuilder.class);
object = constructor.newInstance(new StringBuilder("Hello Universe!"));
System.out.println("String = " + object);
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024