<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Java 11 的新特性和增強特性 > 原文: [https://howtodoinjava.com/java11/features-enhancements/](https://howtodoinjava.com/java11/features-enhancements/) Java 11(于 2018 年 9 月發布)包含許多重要且有用的更新。 讓我們看看它為開發人員和建筑師帶來的新特性和改進。 ## 1\. HTTP 客戶端 API Java 長時間使用`HttpURLConnection`類進行 HTTP 通信。 但是隨著時間的流逝,要求變得越來越復雜,對應用程序的要求也越來越高。 在 Java 11 之前,開發人員不得不訴諸特性豐富的庫,例如 *Apache HttpComponents* 或 *OkHttp* 等。 我們看到 [Java 9](https://howtodoinjava.com/java9/java9-new-features-enhancements/) 版本包含`HttpClient`實現作為實驗特性。 隨著時間的流逝,它已經成為 Java 11 的最終特性。現在,Java 應用程序可以進行 HTTP 通信,而無需任何外部依賴。 #### 1.1 如何使用`HttpClient` 與`java.net.http`模塊的典型 HTTP 交互看起來像: * 創建`HttpClient`的實例,并根據需要對其進行配置。 * 創建`HttpRequest`的實例并填充信息。 * 將請求傳遞給客戶端,執行請求,并檢索`HttpResponse`的實例。 * 處理`HttpResponse`中包含的信息。 HTTP API 可以處理同步和異步通信。 讓我們來看一個簡單的例子。 #### 1.2 同步請求示例 請注意,http 客戶端 API 如何使用**構建器模式**創建復雜的對象。 ```java import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; HttpClient httpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(10)) .build(); try { String urlEndpoint = "https://postman-echo.com/get"; URI uri = URI.create(urlEndpoint + "?foo1=bar1&foo2=bar2"); HttpRequest request = HttpRequest.newBuilder() .uri(uri) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } System.out.println("Status code: " + response.statusCode()); System.out.println("Headers: " + response.headers().allValues("content-type")); System.out.println("Body: " + response.body()); ``` #### 1.2 異步請求示例 如果我們不想等待響應,那么異步通信很有用。 我們提供了回調處理程序,可在響應可用時執行。 注意使用`sendAsync()`方法發送異步請求。 ```java import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; final List<URI> uris = Stream.of( "https://www.google.com/", "https://www.github.com/", "https://www.yahoo.com/" ).map(URI::create).collect(toList()); HttpClient httpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(10)) .followRedirects(HttpClient.Redirect.ALWAYS) .build(); CompletableFuture[] futures = uris.stream() .map(uri -> verifyUri(httpClient, uri)) .toArray(CompletableFuture[]::new); CompletableFuture.allOf(futures).join(); private CompletableFuture<Void> verifyUri(HttpClient httpClient, URI uri) { HttpRequest request = HttpRequest.newBuilder() .timeout(Duration.ofSeconds(5)) .uri(uri) .build(); return httpClient.sendAsync(request,HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::statusCode) .thenApply(statusCode -> statusCode == 200) .exceptionally(ex -> false) .thenAccept(valid -> { if (valid) { System.out.println("[SUCCESS] Verified " + uri); } else { System.out.println("[FAILURE] Could not " + "verify " + uri); } }); } ``` ## 2\. 啟動不編譯的單文件程序 傳統上,對于我們要執行的每個程序,我們都需要先對其進行編譯。 出于測試目的,小型程序似乎不必要地耗時。 Java 11 對其進行了更改,現在我們可以執行單個文件中包含的 Java 源代碼,而無需先對其進行編譯。 ```java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } ``` 要執行上述類,請直接使用`java`命令運行它。 ```java $ java HelloWorld.java Hello World! ``` > 注意,程序**不能使用`java.base module`之外的任何外部依賴項**。 并且該程序只能是**單文件程序**。 ## 3\. 字符串 API 的更改 #### 3.1 `String.repeat(int)` 此方法僅重復[字符串](https://howtodoinjava.com/java-string/)`n`次。 它返回一個字符串,其值是重復 N 次給定字符串的連接。 如果此字符串為空或`count`為零,則返回空字符串。 ```java public class HelloWorld { public static void main(String[] args) { String str = "1".repeat(5); System.out.println(str); //11111 } } ``` #### 3.2 `String.isBlank()` 此方法指示字符串是空還是僅包含空格。 以前,我們一直在 Apache 的`StringUtils.java`中使用它。 ```java public class HelloWorld { public static void main(String[] args) { "1".isBlank(); //false "".isBlank(); //true " ".isBlank(); //true } } ``` #### 3.3 `String.strip()` 此方法需要除去前導和尾隨空白。 通過使用`String.stripLeading()`僅刪除開頭字符,或者使用`String.stripTrailing()`僅刪除結尾字符,我們甚至可以更加具體。 ```java public class HelloWorld { public static void main(String[] args) { " hi ".strip(); //"hi" " hi ".stripLeading(); //"hi " " hi ".stripTrailing(); //" hi" } } ``` #### 3.4 `String.lines()` 此方法有助于將多行文本作為[**流**](https://howtodoinjava.com/java8/java-streams-by-examples/)來處理。 ```java public class HelloWorld { public static void main(String[] args) { String testString = "hello\nworld\nis\nexecuted"; List<String> lines = new ArrayList<>(); testString.lines().forEach(line -> lines.add(line)); assertEquals(List.of("hello", "world", "is", "executed"), lines); } } ``` ## 4\. `Collection.toArray(IntFunction)` 在 Java 11 之前,將集合轉換為數組并不容易。 Java 11 使轉換更加方便。 ```java public class HelloWorld { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("alex"); names.add("brian"); names.add("charles"); String[] namesArr1 = names.toArray(new String[names.size()]); //Before Java 11 String[] namesArr2 = names.toArray(String[]::new); //Since Java 11 } } ``` ## 5\. `Files.readString()`和`Files.writeString()` 使用這些重載方法,Java 11 的目標是減少大量樣板代碼,從而使文件讀寫更加容易。 ```java public class HelloWorld { public static void main(String[] args) { //Read file as string URI txtFileUri = getClass().getClassLoader().getResource("helloworld.txt").toURI(); String content = Files.readString(Path.of(txtFileUri),Charset.defaultCharset()); //Write string to file Path tmpFilePath = Path.of(File.createTempFile("tempFile", ".tmp").toURI()); Path returnedFilePath = Files.writeString(tmpFilePath,"Hello World!", Charset.defaultCharset(), StandardOpenOption.WRITE); } } ``` ## 6\. `Optional.isEmpty()` [`Optional`](https://howtodoinjava.com/java8/java-8-optionals-complete-reference/)是一個容器對象,可能包含也可能不包含非`null`值。 如果不存在任何值,則該對象被認為是空的。 如果存在值,則先前存在的方法`isPresent()`返回`true`,否則返回`false`。 有時,它迫使我們編寫不可讀的負面條件。 `isEmpty()`方法與`isPresent()`方法相反,如果存在值,則返回`false`,否則返回`true`。 因此,在任何情況下我們都不會寫負面條件。 適當時使用這兩種方法中的任何一種。 ```java public class HelloWorld { public static void main(String[] args) { String currentTime = null; assertTrue(!Optional.ofNullable(currentTime).isPresent()); //It's negative condition assertTrue(Optional.ofNullable(currentTime).isEmpty()); //Write it like this currentTime = "12:00 PM"; assertFalse(!Optional.ofNullable(currentTime).isPresent()); //It's negative condition assertFalse(Optional.ofNullable(currentTime).isEmpty()); //Write it like this } } ``` 向我提供有關 Java 11 中這些**新 API 更改的問題**。 學習愉快! 參考: [Java 11 發行文檔](https://docs.oracle.com/en/java/javase/11/)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看