1

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.

Holger
  • 243,335
  • 30
  • 362
  • 661
gparyani
  • 1,872
  • 3
  • 24
  • 35

1 Answers1

7

Class#getConstructor(Object...) javadoc states

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object

Your constructor is not public. It has no access modifier and is therefore package private.

Use getDeclaredConstructor(Object...).

Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683