Class API中的getDeclaredConstructors和getConstructors有什么区别? [英] What is the difference between getDeclaredConstructors and getConstructors in the Class API?

查看:149
本文介绍了Class API中的getDeclaredConstructors和getConstructors有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在Java Reflection API中,有两种不同的调用构造函数的方法: getDeclaredConstructors / getConstructors 方法。尽管Java文档略有不同( getDeclaredConstructors 似乎暗示它返回的是所有构造函数,而不是公共的构造函数),但尚不清楚API为什么显式支持这两种不同的方法。

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?

推荐答案

getDeclaredConstructors (当您需要 all 的所有构造函数时)

getDeclaredConstructors (when you want all the constructors)


返回一个构造函数对象数组,该数组反映该类声明的所有构造函数由该Class对象表示。这些是公共的,受保护的默认(包)访问和私有构造函数。

Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. These are public, protected, default (package) access, and private constructors.

getConstructors (当您只想 public 构造函数时)

getConstructors (when you want only public constructors)


返回一个数组,该数组包含反映此Class对象表示的类的所有公共构造函数的Constructor对象。

Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.

因此,请查看文档他们两个,我认为区别是 getConstructors 仅返回 public 构造函数,而 getDeclaredConstructors 返回所有构造函数( public 受保护的,默认(包)访问权限和 private

So, looking at the docs for both of them, I think a difference is that getConstructors returns only public constructors while getDeclaredConstructors returns all the constructors (public, protected, default (package) access, and private)

因此,如果只需要 public 构造函数,然后使用 getConstructors 。否则,如果需要所有构造函数(不考虑构造函数的访问修饰符),请使用 getDeclaredConstructors

So, it's easy if you need only the public constructors then use getConstructors. Otherwise, if you need all the constructors (disregarding the access-modifier of the constructor) then use getDeclaredConstructors.

这篇关于Class API中的getDeclaredConstructors和getConstructors有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆