Java 中的命名参数习惯用法
如何在 Java 中实现命名参数习惯用法? (特别是对于构造函数)
我正在寻找一种类似 Objective-C 的语法,而不是像 JavaBeans 中使用的语法。
一个小的代码示例就可以了。
How to implement Named Parameter idiom in Java? (especially for constructors)
I am looking for an Objective-C like syntax and not like the one used in JavaBeans.
A small code example would be fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(22)
我认为在构造函数中模拟关键字参数的最佳 Java 习惯是 Builder 模式,如 Effective 中所述。 Java 第二版。
基本思想是拥有一个 Builder 类,该类具有针对不同构造函数参数的 setter(但通常没有 getter)。还有一个
build()
方法。 Builder 类通常是它用来构建的类的(静态)嵌套类。外部类的构造函数通常是私有的。最终结果如下所示:
要创建 Foo 的实例,您可以编写如下内容:
主要警告是:
您可能还想查看 这篇博文(不是我写的)。
The best Java idiom I've seem for simulating keyword arguments in constructors is the Builder pattern, described in Effective Java 2nd Edition.
The basic idea is to have a Builder class that has setters (but usually not getters) for the different constructor parameters. There's also a
build()
method. The Builder class is often a (static) nested class of the class that it's used to build. The outer class's constructor is often private.The end result looks something like:
To create an instance of Foo you then write something like:
The main caveats are:
You may also want to check out this blog post (not by me).
值得一提的是:
所谓的双括号初始化器。它实际上是一个带有实例初始值设定项的匿名类。
This is worth of mentioning:
the so called double-brace initializer. It is actually an anonymous class with instance initializer.
Java 8 风格:
Java 8 style:
您还可以尝试遵循此处的建议。
它在调用站点上很冗长,但总体而言开销最低。
You could also try to follow advice from here.
It's verbose on the call site, but overall gives the lowest overhead.
我想指出的是,这种样式解决了命名参数和属性功能,而没有get和set > 其他语言所具有的前缀。它在 Java 领域并不常见,但它更简单、更短,特别是如果您处理过其他语言的话。
I would like to point out that this style addresses both the named parameter and the properties features without the get and set prefix which other language have. Its not conventional in Java realm but its simpler and shorter, especially if you have handled other languages.
如果您使用的是 Java 6,则可以使用可变参数并导入 static 来产生更好的结果。有关详细信息,请参阅:
http://zinzel。 blogspot.com/2010/07/creating-methods-with-named-parameters.html
简而言之,你可以有类似的东西:
If you are using Java 6, you can use the variable parameters and import static to produce a much better result. Details of this are found in:
http://zinzel.blogspot.com/2010/07/creating-methods-with-named-parameters.html
In short, you could have something like:
怎么样
What about
Java 不支持类似于 Objective-C 的构造函数或方法参数的命名参数。此外,这确实不是 Java 的做事方式。
在java中,典型的模式是对类和成员进行冗长的命名。类和变量应该是名词,方法命名应该是动词。我想您可以发挥创意,偏离 Java 命名约定,以一种黑客的方式模拟 Objective-C 范式,但这不会被负责维护代码的普通 Java 开发人员特别欣赏。
使用任何语言工作时,您都应该遵守语言和社区的惯例,尤其是在团队中工作时。
Java does not support Objective-C-like named parameters for constructors or method arguments. Furthermore, this is really not the Java way of doing things.
In java, the typical pattern is verbosely named classes and members. Classes and variables should be nouns and method named should be verbs. I suppose you could get creative and deviate from the Java naming conventions and emulate the Objective-C paradigm in a hacky way but this wouldn't be particularly appreciated by the average Java developer charged with maintaining your code.
When working in any language, it behooves you to stick to the conventions of the language and community, especially when working on a team.
我觉得“评论解决方法”值得有自己的答案(隐藏在现有答案中并在此处的评论中提到)。
I feel like the "comment-workaround" deserves it's own answer (hidden in existing answers and mentioned in comments here).
Java 中的任何解决方案都可能非常冗长,但值得一提的是 Google 等工具AutoValues 和 Immutables 将使用 JDK 编译时注释处理自动为您生成构建器类。
对于我的情况,我希望在 Java 枚举中使用命名参数,因此构建器模式不起作用,因为枚举实例无法由其他类实例化。我想出了一种类似于@deamon的答案的方法,但添加了参数排序的编译时检查(以更多代码为代价)
这是客户端代码:
以及实现:
Any solution in Java is likely going to be pretty verbose, but it's worth mentioning that tools like Google AutoValues and Immutables will generate builder classes for you automatically using JDK compile time annotation processing.
For my case, I wanted named parameters to use in a Java enum, so a builder pattern wouldn't work because enum instances can't be instantiated by other classes. I came up with an approach similar @deamon's answer but adds compile-time checking of parameter ordering (at the expense of more code)
Here's client code:
And the implementation:
您可以使用项目 Lombok 的 @Builder 注释 来模拟 Java 中的命名参数。这将为您生成一个构建器,您可以使用它来创建任何类的新实例(您编写的类和来自外部库的类)。
这是在类上启用它的方法:
之后您可以通过以下方式使用它:
如果您想为来自库的类创建这样的构建器,请创建一个带注释的静态方法,如下所示:
这将生成一个名为“的方法”构建器”,可以通过以下方式调用:
You can use project Lombok's @Builder annotation to simulate named parameters in Java. This will generate a builder for you which you can use to create new instances of any class (both classes you've written and those coming from external libraries).
This is how to enable it on a class:
Afterwards you can use this by:
If you'd like to create such a Builder for a class coming from a library, create an annotated static method like this:
This will generate a method named "builder" which can be called by:
您可以使用常用的构造函数和静态方法来为参数命名:
用法:
与实际命名参数相比的限制:
/*name*/ "pen", /*size*/ 20, /*weight*/ 8.2)
)如果您可以选择,请查看 Scala 2.8。 http://www.scala-lang.org/node/2075
You could use a usual constructor and static methods that give the arguments a name:
Usage:
Limitations compared to real named parameters:
/*name*/ "pen", /*size*/ 20, /*weight*/ 8.2)
)If you have the choice look at Scala 2.8. http://www.scala-lang.org/node/2075
使用 Java 8 的 lambda,您可以更接近真实命名参数。
请注意,这可能违反了几十个“java 最佳实践”(就像使用
$
符号的任何内容)。优点:
缺点:
Using Java 8's lambdas you can get even closer to real named parameters.
Do note that this probably violates a couple dozen "java best practices" (like anything that makes use of the
$
symbol).Pros:
Cons:
这是上面 Lawrence 所描述的 Builder 模式的变体。
我发现自己经常使用它(在适当的地方)。
主要区别在于,在这种情况下,构建器是不可变的。这样做的优点是可以重用并且是线程安全的。
因此,您可以使用它来创建一个默认构建器,然后在您需要它的各个地方可以配置它并构建您的对象。
如果您一遍又一遍地构建相同的对象,那么这是最有意义的,因为这样您就可以使构建器静态化,而不必担心更改它的设置。
另一方面,如果您必须使用不断变化的参数来构建对象,这会产生一些开销。 (但是,嘿,您可以将静态/动态生成与自定义
build
方法结合起来)以下是示例代码:
This is a variant of the
Builder
Pattern as described by Lawrence above.I find myself using this a lot (at the apropriate places).
The main difference is, that in this case the Builder is immuatable. This has the advantage that it can be reused and is thread-safe.
So you can use this to make one default Builder and then in the various places where you need it you can configure it and build your object.
This makes most sense, if you are building the same object over and over again, because then you can make the builder static and don't have to worry about changing it's settings.
On the other hand if you have to build objects with changing paramaters this has quiet some overhead. (but hey, you can combine static / dynamic generation with custom
build
methods)Here is the example code:
这是一个经过编译器检查的构建器模式。注意事项:
.build()
方法所以你需要类之外的东西,如果不通过<代码>生成器<是,是,是>。请参阅
getSum
静态方法作为示例。注意事项解释。为什么没有构建方法?麻烦的是它会在 Builder 类中,并且会被参数化为 K1、K2、K3 等。由于方法本身必须编译,所以一切它调用必须编译。所以,一般来说,我们不能把编译测试放在类本身的方法中。
出于类似的原因,我们无法阻止使用构建器模型的双重分配。
Here is a compiler-checked Builder pattern. Caveats:
.build()
methodSo you need something outside the class that will fail if not passed
Builder<Yes, Yes, Yes>
. See thegetSum
static method as an example.Caveats explained. Why no build method? The trouble is that it's going to be in the
Builder
class, and it will be parameterized withK1, K2, K3
, etc. As the method itself has to compile, everything it calls must compile. So, generally, we can't put a compilation test in a method of the class itself.For a similar reason, we can't prevent double assignment using a builder model.
现在我们都在 Java 17 上;-),使用记录是模仿这个习惯用法的超级简单的方法:
然后你可以调用:
我发现它非常容易阅读,并且我已经完全停止获取所有 int参数混淆了(“是尺寸优先还是距离……”)。
Now that we're all on Java 17 ;-), using records is a super-easy way to imitate this idiom:
Then you can call:
Which I've found extremely easy to read and I've completely stopped getting all the int parameters mixed up ("was it size first or distance...").
karg 库 支持的习惯用法可能值得考虑:
The idiom supported by the karg library may be worth considering:
您可以模仿应用此模式的命名参数:
然后您可以将其传递给您的方法,如下所示:
您可以在此处阅读更多信息 https://medium.com/@ivorobioff/named-parameters-in-java-9072862cfc8c
You can imitate named parameters applying this pattern:
and then you can pass it to your method as this:
You can read more here https://medium.com/@ivorobioff/named-parameters-in-java-9072862cfc8c
例子
Example
也许可以使用这个:
类:
maybe can use this:
class:
注意我主要在测试中使用它,我想在测试中验证一些东西,但根据您的用例,您可以将参数名称放在方法名称本身中
示例:
或者,您可以向方法添加额外的参数,每个参数前面一个,“命名”它们,
例如
Note I mostly use this in tests, where I want to verify things, but depending on your use case, you could put the parameter names in the method name itself
Example:
or, you can add extra parameters to your method, one before each parameter, to "name" them, e.g.
e.g.
@irreputable 提出了一个很好的解决方案。但是 - 它可能会使您的类实例处于无效状态,因为不会发生验证和一致性检查。因此,我更喜欢将其与构建器解决方案结合起来,避免创建额外的子类,尽管它仍然会子类化构建器类。此外,由于额外的构建器类使其更加冗长,因此我使用 lambda 添加了另一种方法。为了完整性,我添加了一些其他构建器方法。
从一个类开始,如下所示:
然后使用它应用不同的方法:
它看起来在一定程度上完全是抄袭 @LaurenceGonsalves 已经发布的内容,但您会看到所选约定的细微差别。
我想知道,如果 JLS 会实现命名参数,他们会怎么做?他们是否会通过提供简短的支持来扩展现有的习惯用法之一? Scala 如何支持命名参数?
嗯——足够研究了,也许是一个新问题。
@irreputable came up with a nice solution. However - it might leave your Class instance in a invalid state, as no validation and consistency checking will happen. Hence I prefer to combine this with the Builder solution, avoiding the extra subclass to be created, although it would still subclass the builder class. Additionally, because the extra builder class makes it more verbose, I added one more method using a lambda. I added some of the other builder approaches for completeness.
Starting with a class as follows:
Then using this applying the different methods:
It looks like in part a total rip-off from what @LaurenceGonsalves already posted, but you will see the small difference in convention chosen.
I am wonder, if JLS would ever implement named parameters, how they would do it? Would they be extending on one of the existing idioms by providing a short-form support for it? Also how does Scala support named parameters?
Hmmm - enough to research, and maybe a new question.