Reputation: 65
So I am creating a spigot plugin but that's not so important.
I have a Selection class that keeps information about a 2D area with the x,z,width,depth stuff. At a certain point a rectangle or an ellipse will be stuffed into that selection. My Ellipse and Rectangle class implement an interface Shape.
In the consturctor of Selection I'd like to determine the type of later used shape. My first idea was to pass the class type
public Selection(Class<Shape> shapeType) {
so I could just create an object of that class afterwards
Constructor<Shape> cons = shapeType.getConstructor(//Well I also don't know what belongs here);
Shape s = cons.newInstance(this);
Well in the end I got a NullpointerException because the Shape interface does not have a constructor.
I am just confused. Shall I change the Shape interface to an abstract class or just pass some ints like ELLIPSE and RECTANGLE in the constructor? Does anybody have an idea what I could do?
Thanks in advance Mighty One
Upvotes: 1
Views: 100
Reputation: 140318
Don't do this.
What you are trying to do is to pass in "a thing which gives me a thing". What you're actually passing in is "a thing which gives access to things which give you things".
A Class gives you access to zero or more constructors; it doesn't guarantee that there is one you can invoke with particular parameters to give you an instance. The problem that you've found using reflection is that you have no guarantee of the existence of the constructor.
Take a simpler approach: pass in a Supplier<? extends Shape>
, e.g. Rectangle::new
or () -> new Ellipse(10, 20)
. This is checked at compile time to ensure that the constructor exists.
Upvotes: 5