这个techinique有一个名称(方法调用返回对象,在同一行上进行另一个方法调用)?
String pAID = commonAssets.getApplicationServerSettings().getSetting("plivoAuthID");
Run Code Online (Sandbox Code Playgroud)
代替
ApplicationServerSettings applicationServerSettings = commonAssets.getApplicationServerSettings();
String pAID = applicationServerSettings.getSetting("plivoAuthID");
Run Code Online (Sandbox Code Playgroud)
另外,当我第一次执行时,Eclipse不会提示我导入该类ApplicationServerSettings,但如果我使用第二种代码样式,则会执行此操作.
另外,这两种风格仅仅是偏好吗?
该技术称为方法链.
String pAID = commonAssets.getApplicationServerSettings().getSetting("plivoAuthID");
Run Code Online (Sandbox Code Playgroud)
来自wiki的定义:
方法链(也称为命名参数idiom)是用于在面向对象的编程语言中调用多个方法调用的常用语法.每个方法都返回一个对象,允许在单个语句中将调用链接在一起,而不需要变量来存储中间结果.[1] 局部变量声明是语法糖,因为人类在深度嵌套方法调用时遇到困难.[2] [3] 方法链也被称为火车残骸,因为随着更多方法被链接在一起而出现的同一线路中一个接一个地出现的方法的数量增加[4],即使在方法之间经常添加换行符.
你的第二个问题:
另外,当我第一次执行时,Eclipse不会提示我导入类ApplicationServerSettings,但是如果我使用第二种代码样式则会这样做.
ApplicationServerSettings.另一个例子(除了想要介绍之外)看起来更简单:
看一下wiki示例:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |