1. ภาพรวม
ในบทความนี้เราจะมาดูคุณสมบัติใหม่ที่น่าสนใจที่สุดใน Java 8
เราจะพูดถึง: วิธีการเริ่มต้นของอินเทอร์เฟซและวิธีการคงที่การอ้างอิงวิธีการและทางเลือก
เราได้กล่าวถึงคุณลักษณะบางอย่างของ API สตรีมเวอร์ชัน Java 8 นิพจน์แลมบ์ดาและอินเทอร์เฟซการทำงานแล้วเนื่องจากเป็นหัวข้อที่ครอบคลุมซึ่งสมควรได้รับรูปลักษณ์แยกต่างหาก
2. อินเทอร์เฟซเริ่มต้นและวิธีการแบบคงที่
ก่อน Java 8 อินเทอร์เฟซอาจมีเฉพาะเมธอดนามธรรมสาธารณะ เป็นไปไม่ได้ที่จะเพิ่มฟังก์ชันการทำงานใหม่ให้กับอินเทอร์เฟซที่มีอยู่โดยไม่บังคับให้คลาสที่ใช้งานทั้งหมดสร้างการใช้งานเมธอดใหม่และไม่สามารถสร้างเมธอดอินเทอร์เฟซด้วยการนำไปใช้งานได้
เริ่มต้นด้วย Java 8 อินเทอร์เฟซสามารถมีเมธอดแบบสแตติกและดีฟอลต์ที่แม้ว่าจะประกาศในอินเทอร์เฟซ แต่ก็มีพฤติกรรมที่กำหนดไว้
2.1. วิธีคงที่
พิจารณาวิธีการต่อไปนี้ของอินเทอร์เฟซ (ขอเรียกส่วนต่อประสานนี้ว่ายานพาหนะ ):
static String producer() { return "N&F Vehicles"; }
วิธีการผลิตแบบคงที่()มีให้ใช้งานผ่านและภายในอินเทอร์เฟซเท่านั้น ไม่สามารถลบล้างได้โดยคลาสการนำไปใช้งาน
ในการเรียกใช้งานภายนอกอินเทอร์เฟซควรใช้แนวทางมาตรฐานสำหรับการเรียกวิธีการแบบคงที่:
String producer = Vehicle.producer();
2.2. วิธีการเริ่มต้น
วิธีการเริ่มต้นมีการประกาศใช้ใหม่เริ่มต้นคำหลัก สิ่งเหล่านี้สามารถเข้าถึงได้ผ่านอินสแตนซ์ของคลาสการใช้งานและสามารถลบล้างได้
มาเพิ่มวิธีเริ่มต้นให้กับอินเทอร์เฟซพาหนะของเราซึ่งจะโทรไปยังวิธีการคงที่ของอินเทอร์เฟซนี้
default String getOverview() { return "ATV made by " + producer(); }
สมมติว่าอินเทอร์เฟซนี้ใช้งานโดยคลาสVehicleImpl สำหรับการเรียกใช้เมธอดเริ่มต้นควรสร้างอินสแตนซ์ของคลาสนี้:
Vehicle vehicle = new VehicleImpl(); String overview = vehicle.getOverview();
3. การอ้างอิงวิธีการ
การอ้างอิงเมธอดสามารถใช้เป็นทางเลือกที่สั้นกว่าและอ่านง่ายกว่าสำหรับนิพจน์แลมบ์ดาซึ่งเรียกเฉพาะเมธอดที่มีอยู่ การอ้างอิงวิธีการมีสี่รูปแบบ
3.1. อ้างอิงถึงวิธีการคงที่
การอ้างอิงถึงวิธีการแบบคงที่มีไวยากรณ์ต่อไปนี้: ContainingClass :: methodName
ลองนับสตริงว่างทั้งหมดในรายการด้วยความช่วยเหลือของ Stream API
boolean isReal = list.stream().anyMatch(u -> User.isRealUser(u));
ลองดูนิพจน์แลมบ์ดาในเมธอด anyMatch ()ให้ละเอียดยิ่งขึ้นเพียงแค่ทำการเรียกใช้เมธอดแบบคงที่isRealUser (ผู้ใช้ผู้ใช้)ของคลาสUser ดังนั้นจึงสามารถแทนที่ด้วยการอ้างอิงถึงวิธีการคงที่:
boolean isReal = list.stream().anyMatch(User::isRealUser);
รหัสประเภทนี้ดูให้ข้อมูลมากกว่า
3.2. การอ้างอิงถึงวิธีการอินสแตนซ์
การอ้างอิงไปยังวิธีการอินสแตนซ์มีไวยากรณ์ต่อไปนี้: c ontainingInstance :: methodName วิธีการเรียกรหัสต่อไปนี้isLegalName (สตริงสตริง)ประเภทUserซึ่งตรวจสอบความถูกต้องของพารามิเตอร์อินพุต:
User user = new User(); boolean isLegalName = list.stream().anyMatch(user::isLegalName);
3.3. การอ้างอิงถึงวิธีการอินสแตนซ์ของออบเจ็กต์ประเภทเฉพาะ
วิธีการอ้างอิงนี้ใช้ไวยากรณ์ต่อไปนี้: C ontainingType :: methodName ตัวอย่าง::
long count = list.stream().filter(String::isEmpty).count();
3.4. Reference to a Constructor
A reference to a constructor takes the following syntax: ClassName::new. As constructor in Java is a special method, method reference could be applied to it too with the help of newas a method name.
Stream stream = list.stream().map(User::new);
4. Optional
Before Java 8 developers had to carefully validate values they referred to, because of a possibility of throwing the NullPointerException (NPE). All these checks demanded a pretty annoying and error-prone boilerplate code.
Java 8 Optional class can help to handle situations where there is a possibility of getting the NPE. It works as a container for the object of type T. It can return a value of this object if this value is not a null. When the value inside this container is null it allows doing some predefined actions instead of throwing NPE.
4.1. Creation of the Optional
An instance of the Optional class can be created with the help of its static methods:
Optional optional = Optional.empty();
Returns an empty Optional.
String str = "value"; Optional optional = Optional.of(str);
Returns an Optional which contains a non-null value.
Optional optional = Optional.ofNullable(getString());
Will return an Optional with a specific value or an empty Optional if the parameter is null.
4.2. Optional Usage
For example, you expect to get a List and in the case of null you want to substitute it with a new instance of an ArrayList. With pre-Java 8's code you need to do something like this:
List list = getList(); List listOpt = list != null ? list : new ArrayList();
With Java 8 the same functionality can be achieved with a much shorter code:
List listOpt = getList().orElseGet(() -> new ArrayList());
There is even more boilerplate code when you need to reach some object's field in the old way. Assume you have an object of type User which has a field of type Address with a field street of type String. And for some reason you need to return a value of the street field if some exist or a default value if street is null:
User user = getUser(); if (user != null) { Address address = user.getAddress(); if (address != null) { String street = address.getStreet(); if (street != null) { return street; } } } return "not specified";
This can be simplified with Optional:
Optional user = Optional.ofNullable(getUser()); String result = user .map(User::getAddress) .map(Address::getStreet) .orElse("not specified");
In this example we used the map() method to convert results of calling the getAdress() to the Optional and getStreet() to Optional. If any of these methods returned null the map() method would return an empty Optional.
Imagine that our getters return Optional. So, we should use the flatMap() method instead of the map():
Optional optionalUser = Optional.ofNullable(getOptionalUser()); String result = optionalUser .flatMap(OptionalUser::getAddress) .flatMap(OptionalAddress::getStreet) .orElse("not specified");
Another use case of Optional is changing NPE with another exception. So, as we did previously, let's try to do this in pre-Java 8's style:
String value = null; String result = ""; try { result = value.toUpperCase(); } catch (NullPointerException exception) { throw new CustomException(); }
And what if we use Optional? The answer is more readable and simpler:
String value = null; Optional valueOpt = Optional.ofNullable(value); String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
Notice, that how and for what purpose to use Optional in your app is a serious and controversial design decision, and explanation of its all pros and cons is out of the scope of this article. If you are interested, you can dig deeper, there are plenty of interesting articles on the Internet devoted to this problem. This one and this another one could be very helpful.
5. Conclusion
In this article, we are briefly discussing some interesting new features in Java 8.
There are of course many other additions and improvements which are spread across many Java 8 JDK packages and classes.
But, the information illustrated in this article is a good starting point for exploring and learning about some of these new features.
ในที่สุดซอร์สโค้ดทั้งหมดของบทความก็มีอยู่ใน GitHub