java链式调用空指针_java 链式调用
前言
現在很多開源庫或者代碼都會使用鏈式調用。因為鏈式調用在很多時候,都可以使我們的代碼更加簡潔易懂。以下Student類有多數個屬性,讓我們看看非鏈式調用和鏈式調用有何區別。
非鏈式調用
Main類:
/**
* Created by chenxuxu on 17-1-10.
*/
public class Main {
public static void main(String[] args) {
Student stu = new Student();
stu.setAge(22);
stu.setName("chenxuxu");
stu.setGrade("13級");
stu.setNo("123456789");
stu.setMajor("軟件工程");
}
}
Student類:
/**
* 學生類
*
* Created by chenxuxu on 17-1-10.
*/
public class Student {
/**
* 姓名
*/
private String name;
/**
* 年齡
*/
private int age;
/**
* 學號
*/
private String no;
/**
* 年級
*/
private String grade;
/**
* 專業
*/
private String major;
//...此處省略getter&setter
}
鏈式調用
Main類:
/**
* Created by chenxuxu on 17-1-10.
*/
public class Main {
public static void main(String[] args) {
Student.builder()
.stuName("chenxuxu")
.stuAge(22)
.stuGrade("13級")
.stuMajor("軟件工程")
.stuNo("123456789");
}
}
Student類:
/**
* 學生類
*
* Created by chenxuxu on 17-1-10.
*/
public class Student {
/**
* 不能通過new初始化
*/
private Student(){}
public static Builder builder(){
return new Builder();
}
static class Builder{
/**
* 姓名
*/
private String name;
/**
* 年齡
*/
private int age;
/**
* 學號
*/
private String no;
/**
* 年級
*/
private String grade;
/**
* 專業
*/
private String major;
public Builder stuName(String name){
this.name = name;
return this;
}
public Builder stuAge(int age){
this.age = age;
return this;
}
public Builder stuNo(String no){
this.no = no;
return this;
}
public Builder stuGrade(String grade){
this.grade = grade;
return this;
}
public Builder stuMajor(String major){
this.major = major;
return this;
}
}
}
結論
通過鏈式調用后,代碼看起來簡潔易懂。
總結
以上是生活随笔為你收集整理的java链式调用空指针_java 链式调用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅析 NodeJs 的几种文件路径
- 下一篇: java 传递脚本给c_java – J