I'm attempting to use reflection to create a new instance of a class, using Class.getConstructor
, like so:
class Program {
public static void main(String[] args) {
// this throws NoSuchMethodException
Constructor<Point> constructor = Point.class.getConstructor(float.class, float.class);
// but this finds the method
Constructor<Point>[] constructors = (Constructor<Point>[])Point.class.getConstructors();
System.out.println(constructors[0].toString()); // public Point(float,float)
}
}
class Point {
public float x, y;
public Point(float x, float y) {
this.x = x;
this.y = y;
}
}
What am I doing wrong? Why can't I get the constructor by supplying argument types?
Your code is fine. You just need to handle the checked exception by catching it:
try {
Constructor<Point> constructor = Point.class.getConstructor(float.class, float.class);
} catch (NoSuchMethodException e) {
System.out.println("missing constructor");
}
Or declare it in the method signature:
public static void main(String[] args) throws NoSuchMethodException {