Java 是否支持默认参数值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/997482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does Java support default parameter values?
提问by gnavi
I came across some Java code that had the following structure:
我遇到了一些具有以下结构的 Java 代码:
public MyParameterizedFunction(String param1, int param2)
{
this(param1, param2, false);
}
public MyParameterizedFunction(String param1, int param2, boolean param3)
{
//use all three parameters here
}
I know that in C++ I can assign a parameter a default value. For example:
我知道在 C++ 中我可以为参数分配一个默认值。例如:
void MyParameterizedFunction(String param1, int param2, bool param3=false);
Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?
Java 是否支持这种语法?有什么理由为什么这两个步骤的语法更可取吗?
采纳答案by Kathy Van Stone
No, the structure you found is how Java handles it (that is, with overloading instead of default parameters).
不,您找到的结构是 Java 处理它的方式(即,使用重载而不是默认参数)。
For constructors, See Effective Java: Programming Language Guide'sItem 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.
对于构造函数,如果重载变得复杂,请参阅 Effective Java:编程语言指南的第 1 项提示(考虑静态工厂方法而不是构造函数)。对于其他方法,重命名某些情况或使用参数对象会有所帮助。这是当你有足够的复杂性时,区分是困难的。一个明确的情况是您必须使用参数的顺序进行区分,而不仅仅是数字和类型。
回答by Rob H
Sadly, no.
可悲的是没有。
回答by Santosh Gokak
No.
不。
You can achieve the same behavior by passing an Object which has smart defaults. But again it depends what your case is at hand.
您可以通过传递具有智能默认值的对象来实现相同的行为。但这同样取决于您手头的情况。
回答by tomjen
No. In general Java doesn't have much (any) syntactic sugar, since they tried to make a simple language.
不。总的来说,Java 没有太多(任何)语法糖,因为他们试图制作一种简单的语言。
回答by Eli Courtwright
No, but you can use the Builder Pattern, as described in this Stack Overflow answer.
不,但您可以使用Builder Pattern,如此 Stack Overflow answer 中所述。
As described in the linked answer, the Builder Pattern lets you write code like
如链接的答案中所述,构建器模式可让您编写如下代码
Student s1 = new StudentBuilder().name("Eli").buildStudent();
Student s2 = new StudentBuilder()
.name("Spicoli")
.age(16)
.motto("Aloha, Mr Hand")
.buildStudent();
in which some fields can have default values or otherwise be optional.
其中某些字段可以具有默认值或以其他方式可选。
回答by Nicholas Jordan
There are half a dozen or better issues such as this, eventually, you arrive at the static factory pattern ... see the crypto API for that. Sort difficult to explain, but think of it this way: If you have a constructor, default or otherwise, the only way to propagate state beyond the curly braces is either to have a Boolean isValid; ( along with the null as default value v failed constructor ) or throw an exception which is never informative when getting it back from field users.
有六个或更好的问题,例如这样,最终,您会到达静态工厂模式……请参阅加密 API。排序很难解释,但可以这样想:如果你有一个构造函数,无论是默认的还是其他的,在大括号之外传播状态的唯一方法要么是有一个布尔值 isValid;(连同 null 作为默认值 v 构造函数失败)或抛出一个异常,当从现场用户那里取回它时,它永远不会提供信息。
Code Correct be damned, I write thousand line constructors and do what I need. I find using isValid at object construction - in other words, two-line constructors - but for some reason, I am migrating to the static factory pattern. I just seem you can do a lot if you in a method call, there are still sync() issues but defaults can be 'substituted' better ( safer )
代码正确该死,我编写了千行构造函数并做我需要的。我发现在对象构造中使用 isValid - 换句话说,两行构造函数 - 但出于某种原因,我正在迁移到静态工厂模式。如果您在方法调用中,我似乎可以做很多事情,仍然存在 sync() 问题,但可以更好地“替换”默认值(更安全)
I think what we need to do here is address the issue of null as default value vis-a-vis something String one=new String(""); as a member variable, then doing a check for null before assigning string passed to the constructor.
我认为我们在这里需要做的是解决 null 作为默认值的问题,而不是 String one=new String(""); 作为成员变量,然后在分配传递给构造函数的字符串之前检查 null。
Very remarkable the amount of raw, stratospheric computer science done in Java.
用 Java 完成的原始、平流层计算机科学的数量非常惊人。
C++ and so on has vendor libs, yes. Java can outrun them on large scale servers due to it's a massive toolbox. Study static initializer blocks, stay with us.
C++ 等有供应商库,是的。由于它是一个庞大的工具箱,Java 可以在大型服务器上运行它们。研究静态初始化块,和我们在一起。
回答by ebelisle
Unfortunately, yes.
不幸的是,是的。
void MyParameterizedFunction(String param1, int param2, bool param3=false) {}
could be written in Java 1.5 as:
可以用 Java 1.5 写成:
void MyParameterizedFunction(String param1, int param2, Boolean... params) {
assert params.length <= 1;
bool param3 = params.length > 0 ? params[0].booleanValue() : false;
}
But whether or not you should depend on how you feel about the compiler generating a
但是你是否应该取决于你对编译器生成一个
new Boolean[]{}
for each call.
每次通话。
For multiple defaultable parameters:
对于多个默认参数:
void MyParameterizedFunction(String param1, int param2, bool param3=false, int param4=42) {}
could be written in Java 1.5 as:
可以用 Java 1.5 写成:
void MyParameterizedFunction(String param1, int param2, Object... p) {
int l = p.length;
assert l <= 2;
assert l < 1 || Boolean.class.isInstance(p[0]);
assert l < 2 || Integer.class.isInstance(p[1]);
bool param3 = l > 0 && p[0] != null ? ((Boolean)p[0]).booleanValue() : false;
int param4 = l > 1 && p[1] != null ? ((Integer)p[1]).intValue() : 42;
}
This matches C++ syntax, which only allows defaulted parameters at the end of the parameter list.
这匹配 C++ 语法,它只允许参数列表末尾的默认参数。
Beyond syntax, there is a difference where this has run time type checking for passed defaultable parameters and C++ type checks them during compile.
除了语法之外,还有一个不同之处在于它对传递的默认参数进行运行时类型检查,而 C++ 在编译期间对它们进行类型检查。
回答by lythic
You can do this is in Scala, which runs on the JVM and is compatible with Java programs. http://www.scala-lang.org/
您可以在 Scala 中执行此操作,它在 JVM 上运行并与 Java 程序兼容。 http://www.scala-lang.org/
i.e.
IE
class Foo(var prime: Boolean = false, val rib: String) {}
回答by hoaz
It is not supported but there are several options like using parameter object pattern with some syntax sugar:
它不受支持,但有几个选项,例如使用带有一些语法糖的参数对象模式:
public class Foo() {
private static class ParameterObject {
int param1 = 1;
String param2 = "";
}
public static void main(String[] args) {
new Foo().myMethod(new ParameterObject() {{ param1 = 10; param2 = "bar";}});
}
private void myMethod(ParameterObject po) {
}
}
In this sample we construct ParameterObject
with default values and override them in class instance initialization section { param1 = 10; param2 = "bar";}
在此示例中,我们ParameterObject
使用默认值构建并在类实例初始化部分覆盖它们{ param1 = 10; param2 = "bar";}
回答by IronWolf
I might be stating the obvious here but why not simply implement the "default" parameter yourself?
我可能在这里说明了显而易见的问题,但为什么不自己实现“默认”参数呢?
public class Foo() {
public void func(String s){
func(s, true);
}
public void func(String s, boolean b){
//your code here
}
}
for the default, you would either use
默认情况下,您可以使用
func("my string");
and if you wouldn't like to use the default, you would use
如果您不想使用默认值,则可以使用
func("my string", false);