Does Class.getDeclaredConstructor return only public constructors?

Go to the documentation for this method here: getDeclaredConstructor ()

I have not seen any references to it returning only public constructors.

My problem is that I have the following code snippet:

protected BaseClass internalCreate(String className) throws Exception { Class<? extends BaseClass> classObj = Class.forName(className) .asSubclass(BaseClass.class); Constructor<?> ctor = classObj.getDeclaredConstructor((Class[]) null); ctor.setAccessible(true); return (BaseClass) ctor.newInstance(); } 

When I run this method for a class that has the appearance of a default constructor (a closed package), I get a MissingMethod exception. Changing the constructor for the public fixes the problem.

+4
source share
1 answer

This method returns the constructor declared in the class, public or not. But this does not mean that you can install an instance with a return constructor, so you get an error. If access is denied, you call setAccessible (true) on such a constructor. This is the same as with getDeclaredMethod and getDeclaredFields.

+5
source

Source: https://habr.com/ru/post/1484979/


All Articles