I am trying to create new instances of a class (specifically a subclass of an abstract class) by using the forName(String) method.
For example, if I wanted a subclass of Number:
import static java.lang.Class.forName;
import java.lang.reflect.Constructor;
Object[] arguments = new Object[] {0};
String classname = "java.lang.Integer";
try {
Class<? extends Number> c = forName(classname).asSubclass(Number.class);
Constructor<? extends Number> constructor = c.getConstructor(Number.class);
Number x = constructor.newInstance(arguments);
}
catch (Exception e) {
e.printStackTrace();
}
What am I doing wrong?
EDIT: Stacktrace
java.lang.NoSuchMethodException:
java.lang.Integer.<init>(java.lang.Number)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
java.lang.Integerhas not constructor that takes aNumberas its argument.Reading the stacktrace that you got would have told you that (possibly in a slightly cryptic way, but the info is there). You should at least post the stack trace when you’ve got a question about it.