I have the following API code, shortened for brevity:
public class Vec
{
Vec(int x, int y, int z) {/*implementation*/}
//other fields and methods irrelevant to question and not shown
}
Now, I'm trying to write code in a package different from that class above that uses reflection to invoke the constructor of that class and create a new instance of it. Here's what I've tried (code below is in my application's main
method):
Constructor<Vec> c = Vec.class.getConstructor(Integer.TYPE, Integer.TYPE, Integer.TYPE);
c.setAccessible(true);
Vec newVec = c.newInstance(1, 2, 3);
However, when running the above code, I get an exception on the first line in the latter code:
Exception in thread "main" java.lang.NoSuchMethodException: somePackages.Vec.<init>(int, int, int)
Why is it still giving that exception, even if that constructor still exists? I'm running this code using oracle-java8-jdk
on my Raspberry Pi, if that helps.
Class#getConstructor(Object...)
javadoc states
Returns a
Constructor
object that reflects the specifiedpublic
constructor of the class represented by thisClass
object
Your constructor is not public
. It has no access modifier and is therefore package private.
Use getDeclaredConstructor(Object...)
.