Alex Rivera | Logout

What is the difference between getDeclaredConstructors and getConstructors in the Class API?

Asked 2011-11-23T21:16:10.323
78

I notice that in the Java Reflection API there are two different methods for invoking constructors: the getDeclaredConstructors/getConstructors method. Although the Java docs are slightly different (getDeclaredConstructors seems to imply that it returns ALL constructors, rather than public ones), its not clear why the API explicitly supports these two different methods.

More importantly, I'm wondering : when would one method be preferable to another if we are invoking classes dynamically ? For example, what is the purpose of accessing a private constructor?

Edit
Report

1 Answer

7

The getDeclaredXX() methods exist for the manipulation of classes in ways that weren't necessarily intended by the maker of those classes. Note that there is a getDeclaredMethod() method that allows you to invoke private methods, and getDeclaredField() method that allows you to get/set private fields.

I'm not completely sure about "legitimate" use cases, but these are obviously useful for doing certain things. Also, this family of methods only returns things specifically declared in the class, not things that exist in the class because of the superclass.

Accessing a private constructor could be useful for the same reasons, I suppose.

answered 2011-11-23T21:20:34.253

Your Answer