gpt4 book ai didi

java - Class API 中的 getDeclaredConstructors 和 getConstructors 有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 20:28:20 24 4
gpt4 key购买 nike

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

更重要的是,我想知道:如果我们动态调用类,什么时候一种方法比另一种更可取?比如访问私有(private)构造函数的目的是什么?

最佳答案

getDeclaredConstructors (当你想要所有构造函数时)

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 构造函数时)

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

因此,查看它们的文档,我认为不同之处在于 getConstructors 仅返回 public 构造函数,而 getDeclaredConstructors 返回所有构造函数(publicprotected、默认(包)访问和private)

因此,如果您只需要 public 构造函数然后使用 getConstructors 就很容易了。否则,如果您需要所有构造函数(忽略构造函数的访问修饰符),请使用 getDeclaredConstructors

关于java - Class API 中的 getDeclaredConstructors 和 getConstructors 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com