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

前端 未结 4 1521
遥遥无期
遥遥无期 2021-01-30 19:50

I notice that in the Java Reflection API there are two different methods for invoking constructors: the getDeclaredConstructors/getConstructors method.

4条回答
  •  自闭症患者
    2021-01-30 20:30

    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.

提交回复
热议问题