【问题标题】:Determining if a class has a constructor method判断一个类是否有构造方法
【发布时间】:2018-09-15 22:30:30
【问题描述】:

如何判断 Animal 类或 Mammal 类是否有构造函数?

动物 a = new Mammal("Elephant");

【问题讨论】:

  • 构造函数不是方法,如果此代码编译,那么您将调用 Mammal 构造函数,该构造函数采用 String
  • 在文本编辑器中打开 Mammal.java 并阅读它。
  • @ElliottFrisch 实际上构造函数方法,而不是实例方法。
  • @SpencerWieczorek 不符合 Java 语言规范。构造函数是类似于方法的可执行成员,但它们不是方法。
  • @SpencerWieczorek 您正在攀爬的斜坡很滑,我见过权威专家在这方面采取了双向措施。请让我们避免在这样一个微不足道的问题上过于说教,而是关注问题的价值。

标签: java class object constructor


【解决方案1】:

因此,要回答您的问题,所有类都必须至少有一个构造函数,即使其他类无法访问它。

您可以识别开发人员手动添加的构造函数,请参见下面的已声明构造函数的代码示例。 cmets 解释了如何声明构造函数。

public class Animal {

    /*
    *Constructors can be identified in code where the name is the same as the class and has no return type. 
    * The below constructor will require a String to be supplied in order to create an object of type animal.
    */
    public Animal(String name){
        //constructor code goes in here 
    }

}

即使该类没有像下面的示例那样明显声明的构造函数,JVM 也会在编译您的类时生成一个构造函数。

public class Animal {
    /*
     *Just because there is no visible constructor does not mean that one is not available, 
     *By default if no constructor is written a default no argument constructor will be provided after the code is compiled
     *Such that this class can be instantiated as such new Animal() 
     */
}

java 中的默认构造函数将是公共的,并且不提供任何参数,因此上面的示例可以实例化为 new Animal()。

最后,要找出为特定类声明了哪些构造函数,您可以使用 Java 的反射库,下面是一个示例,说明如何访问每个已声明的构造函数。

public class PrintConstructorsForClass {

    public static void main(String[] args) {
        for (Constructor<?> constructor : Animal.class.getDeclaredConstructors()) {
            //Code to inspect each constructor goes in here. 
        }
    }
}   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多