Preface
There is no doubt that Java 8 is the most important version of Java since Java 5 (released in 2004). This version contains more than a dozen new features in languages, compilers, libraries, tools, and JVM.
Java 8 is a major version of Java. Some people believe that although these new features are expected by Java developers, it also requires a lot of effort to learn. Below this article will introduce to you the details of the new features Optional, default methods and static methods in Java 8. Without further ado, let’s take a look at the detailed introduction.
Optional
The Optional class ( java.util.Optional ) is a container class that represents whether a value exists or does not exist. It used to use null to indicate that a value does not exist. Now Optional can better express this concept. And it can avoid null pointer exceptions.
Common methods:
Optional.of(T t) : Creates an Optional instance.Optional.empty() : Creates an empty Optional instance.Optional.ofNullable(T t) If t is not null, create an Optional instance, otherwise create an empty instance.isPresent() : determines whether the value is included.orElse(T t) : Returns the value if the call object contains a value, otherwise returns t.orElseGet(Supplier s) : Returns the value if the call object contains a value, otherwise returns the value obtained by s.map(Function f) If there is a value to process it and returns the processed Optional, otherwise it returns Optional.empty()flatMap(Function mapper) is similar to map, requiring that the return value must be Optional.The following is a paragraph from ImportNew to tell us how to use Optional correctly. For example, don't write it like this:
public static String getName(User u) { Optional<User> user = Optional.ofNullable(u); if (!user.isPresent()) return "Unknown"; return user.get().name;}This rewriting is not only not concise, but also the operation is the same as the first piece of code. It's nothing more than using the isPresent method to replace u==null. Such rewriting is not the correct usage of Optional, let's rewrite it again.
public static String getName(User u) { return Optional.ofNullable(u) .map(user->user.name) .orElse("Unknown");}This is the correct way to use Optional. Then according to this idea, we can make chain calls with peace of mind instead of making judgments layer by layer. Look at a piece of code:
public static String getChampionName(Competition comp) throws IllegalArgumentException { if (comp != null) { CompResult result = comp.getResult(); if (result != null) { User champion = result.getChampion(); if (champion != null) { return champion.getName(); } } } throw new IllegalArgumentException("The value of param comp isn't available.");} Due to various reasons (such as: the competition has not yet produced a championship, abnormal calls to the method, a large gift package buried in the implementation of a certain method, etc.), we cannot happily go all the way comp.getResult().getChampion().getName() . Other languages such as kotlin provide operator blessings at the syntax level: comp?.getResult()?.getChampion()?.getName() So what should we do in Java?
Let's see what these codes will look like after Optional support.
public static String getChampionName(Competition comp) throws IllegalArgumentException { return Optional.ofNullable(comp) .map(c->c.getResult()) .map(r->r.getChampion()) .map(u->u.getName()) .orElseThrow(()->new IllegalArgumentException("The value of param comp isn't available."));}This is very comfortable. The charm of Optional is more than that. Optional also has some magical uses, such as Optional that can be used to test the legality of parameters.
public void setName(String name) throws IllegalArgumentException { this.name = Optional.ofNullable(name).filter(User::isNameValid) .orElseThrow(()->new IllegalArgumentException("Invalid username."));}The above code references importnew - Java8 how to use Optional correctly.
Default and static methods in interfaces
Static methods can be added to the Java8 interface, or default methods can be added, and the default methods are modified with default.
public interface Fun<T> { default void getName(){ System.out.println("hello world"); } static void getAge(){ System.out.println("nine"); }}If an interface defines a default method, a parent class of its implementation class defines a method with the same name and parameter list. Then when the implementation class is called, the method in the parent class is executed.
public class TestF { public void getName(){ System.out.println("TestF"); }}public interface TestInterface { default void getName(){ System.out.println("hello world"); }}public class Test extends TestF implements TestInterface{ public static void main(String[] args) { Test t = new Test(); t.getName();//The output is TestF }}If an implementation class implements two interfaces, if one parent interface provides a default method and the other parent interface also provides a method with the same name and parameter list (regardless of whether the method is the default method), the method must be overridden to resolve the conflict, otherwise an error will be reported.
public interface TestInterface { default void getName(){ System.err.println("hello world"); }}public interface TestInterface1 { void getName();}public class Test1 implements TestInterface, TestInterface1{ public void getName(){ System.out.println("Tes1F"); }}Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.