Thank you for linking me to those two topics - I’ve read them carefully and with some more research, I understood why I have to use .getDeclaredConstructor
and give it the sketch’s class as an argument.
So now, following your implementation from this topic: How do you choose what class you add to a list with a variable?, I had added this to the beginning of my sketch go get its class:
final Class<? extends PApplet> sketchClass = getClass();
and changed the code in the method to
Ingredient ingredient = ingredientClass.getDeclaredConstructor(sketchClass).newInstance(this);
That got me an IllegalArgumentException: argument type mismatch
, so I printed the stack trace of the Exception and got this:
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at ice_creamillionaire$PlayerCharacter$Inventory.add(ice_creamillionaire.java:802)
at ice_creamillionaire$PlayerCharacter.interact(ice_creamillionaire.java:771)
at ice_creamillionaire.keyPressed(ice_creamillionaire.java:55)
at processing.core.PApplet.keyPressed(PApplet.java:2772)
at processing.core.PApplet.handlekeyEvent(PApplet.java:2636)
at processing.core.PApplet.dequeueEvents(PApplet.java:2262)
at processing.core.PApplet.handleDraw(PApplet.java:2104)
at processing.awt.PSurfaceAWT$9.callDraw(PSurfaceAWT.java:1388)
at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:356)
I checked the documentation of newInstance
to see what the problem could be, and I read that the parameters of newInstance
are
an array of objects to be passed as arguments to the constructor call
Now knowing that, I thought that because I was calling zero-argument constructors, I should try calling newInstance
without any arguments. I did that, but it got me an IllegalArgumentException: wrong number of arguments
with the same stack trace. After that, I looked at the code in your implementations again, but I can’t figure out what I’m doing wrong, and I’d be very thankful for some more help.