import java.lang.reflect.*;
public class Test {
public Test(int x) {
System.out.println("Constuctor called! x = " + x);
}
public static void main(String[] args) throws Exception {
Class<? extends Thing> clazz = Stuff.class;
Constructor<? extends Thing> ctor = clazz.getConstructor(int.class);
Thing instance = ctor.newInstance(5);
}
}
public class Thing{
public Thing(int x){
System.out.println("Constructor! x = " + x);
}
}
public class Stuff extends Thing{
public Stuff(int x){
super(x*2);
}
}
The code above works as expected.
import java.lang.reflect.*;
public class Test {
public Test(int x) {
System.out.println("Constuctor called! x = " + x);
}
static void Create(){
Class<? extends Thing> clazz = Stuff.class;
Constructor<? extends Thing> ctor = clazz.getConstructor(int.class);
Thing instance = ctor.newInstance(5);
}
public static void main(String[] args) throws Exception {
Create();
}
}
public class Thing{
public Thing(int x){
System.out.println("Constructor! x = " + x);
}
}
public class Stuff extends Thing{
public Stuff(int x){
super(x*2);
}
}
This code does not. I get these errors:
/tmp/java_tXpJ5P/Test.java:11: error: unreported exception NoSuchMethodException; must be caught or declared to be thrown
Constructor<? extends Thing> ctor = clazz.getConstructor(int.class);
^
/tmp/java_tXpJ5P/Test.java:12: error: unreported exception InstantiationException; must be caught or declared to be thrown
Thing instance = ctor.newInstance(5);
^
2 errors
Am I missing something very obvious or something very arcane here? It just seems bizarre. This is a simplification of code in a much more complex project that is structured slightly differently (and I'm passing Class as an argument) but produces the same errors.
Thanks very much