简体   繁体   English

如何在构造中设置默认参数值?

[英]can I set default parameter value in construture?

Can I set the default arument value in Construct function something like ? 我可以在Construct函数中设置默认的arument值吗?

public class XLSReader {
  public XLSReader(String filename="XYZ.xls") {
  }
}

No. Java doesn't support optional parameters. 否。Java不支持可选参数。 You can use overloading and chaining though: 您可以使用重载和链接:

public XlsReader() {
    this("XYZ.xls");
}

public XlsReader(String filename) {
    // Use filename here
}

(This applies to methods as well as constructors.) (这适用于方法以及构造函数。)

No, you can't. 不,你不能。 Default parameter is not supported in Java. Java不支持默认参数。

No you cannot but what you can do is to have 2 constructors like this: 不,您不能,但是您可以做的是拥有2个这样的构造函数:

public class XLSReader {
  String filename;

  // constructor with a filename argument
  public XLSReader(String filename) {
     this.filename = filename;
  }

  // default constructor will fill-in "default value" XYZ.xls
  public XLSReader() {
     this.filename = "XYZ.xls";
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以将 null 设置为 Spring 中 @Value 的默认值吗? - Can I set null as the default value for a @Value in Spring? 通过代码设置报告的默认参数值 - Set the default parameter value for the report by code 如果第一个属性不是 null 但为空,我可以在占位符中设置默认值吗? - Can I set default value in a placeholder if the first property is not null but is empty? 如何创建一个空地图并设置默认值 - How can I create an Empty Map and set the default value 如何获取非大小写类的构造函数参数的默认值? - How can I obtain the default value of a constructor parameter for a non-case class? 如何设置Maven数组参数的默认值? - How to set the default-value for a maven array parameter? 如何设置Spring Data JPA查询方法必须始终设置为true的参数值? - How can I set that a Spring Data JPA query method have to be a parameter value always set as true? 如何在Spring MVC中设置默认值以获取数组参数 - How to set default value to get array parameter in Spring MVC 如何为jdbc inbound-channel-adapter设置默认参数值? - How to set the default parameter value for jdbc inbound-channel-adapter? Java枚举类可以设置默认值吗 - Can Java enum class set default value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM