gpt4 book ai didi

java - 你把这个称作什么?

转载 作者:行者123 更新时间:2023-11-29 10:11:29 25 4
gpt4 key购买 nike

是否有此技术的名称(方法调用返回对象,在同一行上对其进行另一个方法调用)?

String pAID = commonAssets.getApplicationServerSettings().getSetting("plivoAuthID");

代替

ApplicationServerSettings applicationServerSettings = commonAssets.getApplicationServerSettings();
String pAID = applicationServerSettings.getSetting("plivoAuthID");

此外,当我执行第一个时,Eclipse 不会提示我导入类 ApplicationServerSettings,但如果我使用第二个代码样式,它会提示。

另外,这两种风格仅仅是偏好吗?

最佳答案

该技术称为 method chaining .

String pAID = commonAssets.getApplicationServerSettings().getSetting("plivoAuthID");

来自维基的定义:

Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.[1] Local variable declarations are syntactic sugar because of the difficulty humans have with deeply nested method calls.[2][3] A method chain is also known as a train wreck due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together[4] even though line breaks are often added between methods.

你的第二个问题:

此外,当我执行第一个时,Eclipse 不会提示我导入类 ApplicationServerSettings,但如果我使用第二个代码样式,它会提示。

  • 再次从定义“每个方法返回一个对象,允许调用在一个语句中链接在一起,而不需要变量来存储中间结果。”这就是它不提示你的原因导入类 ApplicationServerSettings

另一个看起来更简单的例子(除了你介绍的want):

看看维基示例:

class Person {
private String name;
private int age;

// In addition to having the side-effect of setting the attributes in question,
// the setters return "this" (the current Person object) to allow for further chained method calls.

public Person setName(String name) {
this.name = name;
return this;
}

public Person setAge(int age) {
this.age = age;
return this;
}

public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}

// Usage:
public static void main(String[] args) {
Person person = new Person();
// Output: Hello, my name is Peter and I am 21 years old.
person.setName("Peter").setAge(21).introduce();
}
}

关于java - 你把这个称作什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32405359/

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