日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java反射api研究_深入研究Java 8中的可选类API

發布時間:2023/12/3 java 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java反射api研究_深入研究Java 8中的可选类API 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

java反射api研究

作為Java程序員,我們所有人都經歷了以下情況:我們調用一個方法來獲取某個值,然后代替直接對返回值調用某些方法,我們首先必須檢查返回值是否不為null,然后在返回值。 這是像Guava這樣的外部API試圖解決的難題 。 此外,其他JVM語言(例如Scala,Ceylon和其他語言)也將這些功能引入了核心API。 在我以前的文章中,我寫了關于一種這樣的JVM語言(即Scala)的支持的文章 。

Java的較新版本(即Java 8)引入了一個名為Optional的新類。 可選類的Javadoc說:

可以包含或不包含非null值的容器對象。 如果存在值,則isPresent()將返回true,而get()將返回該值。

在這篇文章中,讓我們看一下Optional類中存在的每個方法,并用一個或兩個示例進行解釋。

of

返回帶有指定的當前非空值的Optional。

此方法是用于創建Optional類的實例的工廠方法。 這里要注意的一點是,傳遞給創建實例的值必須為非null。 如果傳遞的值為null,則拋出NullPointerException 。

//Creating an instance of Optional using the factory method. Optional<String> name = Optional.of("Sanaulla"); //This fails with a NullPointerException. Optional<String> someNull = Optional.of(null);

ofNullable

返回描述指定值的Optional,如果非空,則返回空值。

與of方法類似,唯一的區別是此方法還處理空值。 一個例子:

//This represents an instance of Optional containing no value //i.e the value is 'null' Optional empty = Optional.ofNullable(null);

isPresent

很簡單的理解:

如果存在值,則返回true,否則返回false。

就像是:

//isPresent method is used to check if there is any //value embedded within the Optional instance. if (name.isPresent()) {//Invoking get method returns the value present//within the Optaional instance.System.out.println(name.get());//prints Sanaulla }

get

如果此Optional中存在一個值,則返回該值,否則拋出NoSuchElementException。

此方法用于檢索Optional實例中存在的值。 我們在上面看到了一個這樣的例子。 讓我們看一個拋出NoSuchElementException的例子:

//The below code prints: No value present try {//Invoking get method on an empty Optaional instance //throws NoSuchElementException.System.out.println(empty.get()); } catch (NoSuchElementException ex) {System.out.println(ex.getMessage()); }

ifPresent

如果存在值,請使用該值調用指定的使用者,否則不執行任何操作。

要了解此方法,您必須了解Consumer類 。 簡而言之,Consumer是一個具有單個抽象方法的類,用于消費一些值并對其執行一些操作而不返回任何值。 在Java 8中,可以將lambda表達式傳遞給期望使用Consumer接口的方法。
如果Optional實例中存在該值,則上述方法接受代碼/ lambda表達式塊以執行某些操作。 就像是:

//ifPresent method takes a lambda expression as a parameter. //The lambda expression can then consume the value if it is present //and perform some operation with it. name.ifPresent((value) -> {System.out.println("The length of the value is: " + value.length()); });

orElse

返回值(如果存在),否則返回其他。

此方法要么返回Optional實例中存在的值,否則返回返回作為參數傳遞給orElse方法的值。 讓我們看一個例子:

//orElse method either returns the value present in the Optional instance //or returns the message passed to the method in case the value is null. //prints: There is no value present! System.out.println(empty.orElse("There is no value present!")); //prints: Sanaulla System.out.println(name.orElse("There is some value!"));

orElseGet

該方法類似于上述方法。 區別在于如何獲取默認值。 在orElse方法中,我們傳遞了固定的字符串作為默認值,但在orElseGet方法中,我們傳遞了Supplier接口的實現,該接口具有一種用于生成默認值的方法。 讓我們看一個例子:

//orElseGet is similar to orElse with a difference that instead of passing //a default value, we pass in a lambda expression which generates the default //value for us. //prints: Default Value System.out.println(empty.orElseGet(() -> "Default Value")); //prints: Sanaulla System.out.println(name.orElseGet(() -> "Default Value"));

orElseThrow

返回包含的值(如果存在),否則拋出異常,由提供的供應商創建。

就像在方法orElseGet我們通過一個供應商的接口 ,但在orElseThrow方法我們通過lambda表達式/方法引用拋出一個異常時,未找到該值。 一個例子:

try {//orElseThrow similar to orElse method, instead of returning a default//value, this method throws an exception which is generated from //the lambda expression/method reference passed as a param to the method.empty.orElseThrow(ValueAbsentException::new); } catch (Throwable ex) {//prints: No value present in the Optional instanceSystem.out.println(ex.getMessage()); }

而且ValueAbsentException的定義是:

class ValueAbsentException extends Throwable {public ValueAbsentException() {super();}public ValueAbsentException(String msg) {super(msg);}@Overridepublic String getMessage() {return "No value present in the Optional instance";} }

map

從有關地圖方法的文檔中:

如果存在值,則將提供的映射函數應用于該值,如果結果為非null,則返回描述結果的Optional。 否則,返回一個空的Optional。

此方法用于對Optional實例中存在的值應用一組操作。 這組操作以lambda表達式的形式傳遞,該表達式表示Function接口的實現。 如果您不熟悉Function接口,那么請花一些時間在這里閱讀我以前關于同一主題的博客文章。 讓我們看一下map方法的示例:

//map method modifies the value present within the Optional instance //by applying the lambda expression passed as a parameter. //The return value of the lambda expression is then wrapped into another //Optional instance. Optional<String> upperName = name.map((value) -> value.toUpperCase()); System.out.println(upperName.orElse("No value found"));

flatMap

從flatMap方法的文檔中:

如果存在一個值,則對它應用提供的帶有可選參數的映射函數,返回該結果,否則返回一個空的Optional。 此方法與map(Function)相似,但是提供的映射器是其結果已經是Optional的映射器,如果調用它,則flatMap不會使用附加的Optional對其進行包裝。

此方法與map方法非常相似,不同之處在于傳遞給它的映射函數的返回類型。 在使用map方法的情況下,映射函數的返回值可以是任何類型T ,而在使用flatMap方法的情況下,映射函數的返回值只能是Optional類型的

讓我們看一下上面的示例,其中將map方法重寫為flatMap方法:

//flatMap is exactly similar to map function, the differece being in the //return type of the lambda expression passed to the method. //In the map method, the return type of the lambda expression can be anything //but the value is wrapped within an instance of Optional class before it //is returned from the map method, but in the flatMap method the return //type of lambda expression's is always an instance of Optional. upperName = name.flatMap((value) -> Optional.of(value.toUpperCase())); System.out.println(upperName.orElse("No value found"));//prints SANAULLA

filter

通過將要應用于值的條件傳遞給filter方法,該方法用于將值限制在Optional實例內。 該文檔說:

如果存在一個值,并且該值與給定謂詞匹配,則返回描述該值的Optional,否則返回一個空的Optional。

到現在為止,您必須已經知道如何將一些代碼塊傳遞給該方法。 是的,它是lambda表達式。 對于這種方法,我們必須傳遞一個lambda表達式,該表達式將是Predicate接口的實現。 如果您不熟悉謂詞界面,請花一些時間閱讀這篇文章。

現在,讓我們看一下filter方法的不同用法,即滿足條件和不滿足條件的兩個示例。

//filter method is used to check if the given optional value satifies //some condtion. If it satifies the condition then the same Optional instance //is returned, otherwise an empty Optional instance is returned. Optional<String> longName = name.filter((value) -> value.length() > 6); System.out.println(longName.orElse("The name is less than 6 characters"));//prints Sanaulla//Another example where the value fails the condition passed to the //filter method. Optional<String> anotherName = Optional.of("Sana"); Optional<String> shortName = anotherName.filter((value) -> value.length() > 6); //prints: The name is less than 6 characters System.out.println(shortName.orElse("The name is less than 6 characters"));

這樣,我就向您介紹了Optional類中存在的各種方法。 讓我將以上所有示例匯總為一個示例,如下所示:

public class OptionalDemo {public static void main(String[] args) {//Creating an instance of Optional//This value can also be returned from some method. Optional<String> name = Optional.of("Sanaulla");//This represents an instance of Optional containing no value//i.e the value is 'null'Optional empty = Optional.ofNullable(null);//isPresent method is used to check if there is any //value embedded within the Optional instance.if (name.isPresent()) {//Invoking get method returns the value present//within the Optaional instance.System.out.println(name.get());}try {//Invoking get method on an empty Optaional instance //throws NoSuchElementException.System.out.println(empty.get());} catch (NoSuchElementException ex) {System.out.println(ex.getMessage());}//ifPresent method takes a lambda expression as a parameter.//The lambda expression can then consume the value if it is present//and perform some operation with it.name.ifPresent((value) -> {System.out.println("The length of the value is: " + value.length());});//orElse method either returns the value present in the Optional instance//or returns the message passed to the method in case the value is null.System.out.println(empty.orElse("There is no value present!"));System.out.println(name.orElse("There is some value!"));//orElseGet is similar to orElse with a difference that instead of passing //a default value, we pass in a lambda expression which generates the default //value for us.System.out.println(empty.orElseGet(() -> "Default Value"));System.out.println(name.orElseGet(() -> "Default Value"));try {//orElseThrow similar to orElse method, instead of returning a default//value, this method throws an exception which is genereated from //the lambda expression/method reference passed as a param to the method.empty.orElseThrow(ValueAbsentException::new);} catch (Throwable ex) {System.out.println(ex.getMessage());}//map method modifies the value present within the Optional instance//by applying the lambda expression passed as a parameter. //The return value of the lambda expression is then wrapped into another//Optional instance.Optional<String> upperName = name.map((value) -> value.toUpperCase());System.out.println(upperName.orElse("No value found"));//flatMap is exactly similar to map function, the differece being in the//return type of the lambda expression passed to the method.//In the map method, the return type of the lambda expression can be anything//but the value is wrapped within an instance of Optional class before it //is returned from the map method, but in the flatMap method the return //type of lambda expression's is always an instance of Optional.upperName = name.flatMap((value) -> Optional.of(value.toUpperCase()));System.out.println(upperName.orElse("No value found"));//filter method is used to check if the given optional value satifies//some condtion. If it satifies the condition then the same Optional instance//is returned, otherwise an empty Optional instance is returned.Optional<String> longName = name.filter((value) -> value.length() > 6);System.out.println(longName.orElse("The name is less than 6 characters"));//Another example where the value fails the condition passed to the //filter method.Optional<String> anotherName = Optional.of("Sana");Optional<String> shortName = anotherName.filter((value) -> value.length() > 6);System.out.println(shortName.orElse("The name is less than 6 characters"));}}

以及上面代碼的輸出:

Sanaulla No value present The length of the value is: 8 There is no value present! Sanaulla Default Value Sanaulla No value present in the Optional instance SANAULLA SANAULLA Sanaulla The name is less than 6 characters

參考:在Experiences Unlimited博客上,我們的JCG合作伙伴 Mohamed Sanaulla深入研究了Java 8中的Optional類API 。

翻譯自: https://www.javacodegeeks.com/2013/09/deep-dive-into-optional-class-api-in-java-8.html

java反射api研究

總結

以上是生活随笔為你收集整理的java反射api研究_深入研究Java 8中的可选类API的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。