- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
是否有此技术的名称(方法调用返回对象,在同一行上对其进行另一个方法调用)?
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/
我是一名优秀的程序员,十分优秀!