java功能模块





Keeping up with the six-month cycle tradition, after the release of Java 13 on September 17, 2019, Java 14, another non-LTS version is scheduled to release on March 17, 2020.

遵循六个月的周期传统,在2019年9月17日发布Java 13 Java 14之后,计划在2020年3月17日发布另一个非LTS版本。

(Java 14 Features)

Here’s the list of Java 14 features:

以下是Java 14功能的列表:





  • Switch Expressions (Standard) – JEP 361
  • Pattern Matching for instanceof (Preview) – JEP 305 instanceof的模式匹配(预览)– JEP 305
  • Helpful NullPointerExceptions – JEP 358 有用的NullPointerExceptions – JEP 358
  • Records (Preview) – JEP 359
  • Text Blocks (Second Preview) – JEP 368
  • Packaging Tool (Incubator) – JEP 343
  • NUMA-Aware Memory Allocation for G1 – JEP 345
  • JFR Event Streaming – JEP 349
  • Non-Volatile Mapped Byte Buffers – JEP 352
  • ZGC on macOS – JEP 364
  • ZGC on Windows – JEP 365
  • Foreign-Memory Access API (Incubator) – JEP 370

(Java 14 Installation Setup on Mac OS)

  • To get started with Java 14, download the JDK from here. 要开始使用Java 14,请从此处下载JDK。
  • Copy and extract the tar file in the /Library/Java/JavaVirtualMachines as shown below: 复制/解压缩tar文件到/Library/Java/JavaVirtualMachines ,如下所示:
$ cd /Library/Java/JavaVirtualMachines

$ sudo cp ~/Downloads/openjdk-14_osx-x64_bin.tar.gz /Library/Java/JavaVirtualMachines

$ sudo tar xzf openjdk-14_osx-x64_bin.tar.gz

$ sudo rm openjdk-14_osx-x64_bin.tar.gz

Once that’s done, open the bash_profile using any text editor. I’m using vim ~/.bash_profile. Set the path of Java14 to JAVA_HOME, save changes and do a source ~/.bash_profile to reflect the changes.

完成后,使用任何文本编辑器打开bash_profile 。 我正在使用vim ~/.bash_profile 。 将Java14的路径设置为JAVA_HOME,保存更改并执行source ~/.bash_profile以反映更改。

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home

Finally, you’re ready to compile and run programs using Java 14. We’ll be using JShell, an interactive REPL command-line tool for quickly testing the new Java 14 features.

最后,您准备使用Java 14编译和运行程序。我们将使用JShell (一种交互式REPL命令行工具),用于快速测试Java 14的新功能。

It’s important to note that many features released in Java 14 are in preview. This means that though they’re fully working right now, things may be modified in the future. Some could be made a standard or simply removed in the next release cycles. In order to test preview features, you need to explicitly set --enable-preview when running the JShell or Java Program as shown below:

重要的是要注意,Java 14中发布的许多功能都处于预览状态。 这意味着尽管它们现在可以完全正常工作,但将来可能会对其进行修改。 有些可以成为标准,也可以在下一个发布周期中简单删除。 为了测试预览功能,在运行JShell或Java程序时,您需要显式设置--enable-preview ,如下所示:

jshell --enable-preview

javac --release 14 --enable-preview Author.java

In the next few sections, let’s discuss some of the language and JVM features.

在接下来的几节中,让我们讨论一些语言和JVM功能。





(1. Switch Expressions)

Switch Expressions after staying a preview feature in the last two releases –Java 12 and Java 13 have finally attained permanent status in Java 14.

在最后两个版本中保留了预览功能后,“开关表达式” – Java 12和Java 13终于在Java 14中获得永久地位。

  • Java 12 introduced the lambda syntax for switch expressions thereby allowing multiple case labels for pattern matching as well as preventing fall-throughs which lead to verbose code. It also enforced exhaustive cases wherein a compilation error would be thrown if all the input cases aren’t covered. Java 12为开关表达式引入了lambda语法,从而允许使用多个大小写标签进行模式匹配以及防止导致冗长代码的失败。 它还强制执行详尽的案例,如果不涵盖所有输入案例,将引发编译错误。
  • Java 13, the second preview introduced yield statements instead of break for returning values from an expression. Java 13 ,第二个预览版引入了yield语句,而不是break来从表达式返回值。

Java 14 has finally made these features a standard now.

Java 14现在终于使这些功能成为标准。

String result = switch (day) {
            case "M", "W", "F" -> "MWF";
            case "T", "TH", "S" -> "TTS";
            default -> {
                if(day.isEmpty())
                    yield "Please insert a valid day.";
                else
                    yield "Looks like a Sunday.";
            }

        };
System.out.println(result);




java 功能业务模块 java功能模块图_python


Java 14 Switch Expressions Java 14开关表达式

Note: Yield isn’t a new keyword in Java. It’s just used in switch expressions.

注意 :Yield不是Java中的新关键字。 它仅用于开关表达式中。

(2. Pattern Matching for instanceof (Preview))

Ask any Java developer to show their codebase and you’ll a good use of instanceof conditions throughout the code. Specifically, an instanceof conditional check is generally followed by a typecasting.

让任何Java开发人员展示他们的代码库,您将在整个代码中很好地使用instanceof条件。 具体而言,通常在条件检查的实例之后进行类型转换。

Java 14, gets rid of this verbosity by making conditional extraction a lot more concise.

Java 14通过使条件提取更加简洁而摆脱了这种冗长的说法。

Before Java 14:

在Java 14之前:

if (obj instanceof Journaldev) {
  Journaldev jd = (Journaldev) obj;
  System.out.println(jd.getAuthor());
}

Java 14 Onwards:

Java 14以上:

if (obj instanceof Journaldev jd) {
  System.out.println(jd.getAuthor());
}

In the above code, the instance jd would be only assigned if obj is of type Journaldev. The scope of the variable is limited to the conditional block only.

在上面的代码中,仅当objJournaldev类型时才分配实例jd 。 变量的范围仅限于条件块。

(3. Helpful NullPointerExceptions)

Null Pointer Exceptions are a nightmare for any developer. Previously, until Java 13, it was tricky to debug the infamous NPEs. Developers had to fall onto other debugging tools or manually figure the variable/method that was null since the stack trace would only show the line number.

空指针异常是任何开发人员的噩梦。 以前,直到Java 13为止,调试臭名昭著的NPE都很棘手。 开发人员不得不依靠其他调试工具,或者手动计算为空的变量/方法,因为堆栈跟踪只会显示行号。

Before Java 14:

在Java 14之前:

String name = jd.getBlog().getAuthor()

//Stacktrace
Exception in thread "main" java.lang.NullPointerException
    at NullPointerExample.main(NullPointerExample.java:5)

Java 14 introduced a new JVM feature which gives better insights with a more descriptive stack as shown below:

Java 14引入了新的JVM功能,它通过更具描述性的堆栈提供了更好的见解,如下所示:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Blog.getAuthor()" because the return value of "Journaldev.getBlog()" is null
    at NullPointerExample.main(NullPointerExample.java:4)

Note: The above feature is not a language feature. It’s an enhancement in the runtime environment.

注意 :以上功能不是语言功能。 这是对运行时环境的增强。

(4. Records (Preview))

A record is a data class that stores pure data. The idea behind introducing records is to quickly create simple and concise classes devoid of boilerplate code.

记录是存储纯数据的数据类。 引入记录背后的想法是快速创建没有样板代码的简单简洁类。


Normally a class in Java would require you to implement equals()hashCode() , the getters and setters methods. While some IDEs support auto-generation of such classes, the code is still verbose. With a record you need to simply define a class in the following way.

通常,Java中的类需要您实现equals()hashCode() ,getters和setters方法。 尽管某些IDE支持此类的自动生成,但是代码仍然很冗长。 使用record您只需按照以下方式简单地定义一个类。

record Author(){}
//or
record Author (String name, String topic) {}

The Java compiler will generate a constructor, private final fields, accessors, equals/hashCode and toString methods automatically. The auto-generated getter methods of the above class are name() and topic().

Java编译器将自动生成一个构造函数,私有最终字段,访问器, equals / hashCodetoString方法。 上一类的自动生成的getter方法是name()topic()

To look into the generated code, use javap Author after you’ve compiled the program using javac. The following illustration shows the generated class for record Author (String name, String topic) {}:

要查看生成的代码,请在使用javac编译程序后使用javap Author 。 下图显示了为record Author (String name, String topic) {}生成的类:


java 功能业务模块 java功能模块图_python_02

Javap Records Java 14

Javap记录Java 14

Furthermore, we can add additional fields, methods, and constructor to the record in the following way:

此外,我们可以通过以下方式向记录添加其他字段,方法和构造函数:

record Author (int id, String name, String topic) {
    static int followers;

    public static String followerCount() {
        return "Followers are "+ followers;
    }

    public String description(){
        return "Author "+ name + " writes on "+ topic;
    }

    public Author{
    if (id < 0) {
        throw new IllegalArgumentException( "id must be greater than 0.");
     }
   }
}

The additional constructor defined inside the record is called a Compact constructor. It doesn’t consist of any parameters and is just an extension of the canonical constructor.

记录内定义的其他构造函数称为Compact构造函数。 它不包含任何参数,只是规范构造函数的扩展。

A compact constructor wouldn’t be generated as a separate constructor by the compiler. Instead, it is used for validation cases and would be invoked at the start of the main constructor.

紧凑的构造函数不会由编译器作为单独的构造函数生成。 而是将其用于验证案例,并将在主构造函数的开头调用。

Few important things to note about Records:

关于记录需要注意的几件事:

  • A record can neither extend a class nor it can be extended by another class. It’s a final class.
  • Records cannot be abstract
  • Records cannot extend any other class and cannot define instance fields inside the body. Instance fields must be defined in the state description only
  • Declared fields are private and final
  • The body of a record allows static fields and methods

Recommended Reading: Java Records

推荐读物Java记录

(4.1) Values Inside Reference Fields Of A Record Can Be Mutated)

It’s important to note that for fields defined which are objects, only the reference is immutable. The underlying values can be modified. The following illustration shows a record in which the ArrayList is modified. As you can see, the value is modified whenever the ArrayList is changed.

重要的是要注意,对于定义为对象的字段,只有引用是不可变的。 基础值可以修改。 下图显示了修改ArrayList的记录。 如您所见,只要更改ArrayList,就将修改该值。


java 功能业务模块 java功能模块图_python_03

Java 14 Records Mutable Values For References

Java 14记录可变值以供参考

(4.2) Records Can Implement Interfaces)

The following code shows an example of implementing an interface with records:

以下代码显示了使用记录实现接口的示例:

record Author(String name, String topic) implements Information {
  public String getFullName() {
    return "Author "+ name + " writes on " + topic;
  }
}

interface Information {
  String getFullName();
}

Here’s the output of the above code in action in a JShell:

这是上述代码在JShell中的实际输出:


java 功能业务模块 java功能模块图_大数据_04

Java 14 Records With Interface 带接口的Java 14记录


(4.3) Records support multiple constructors)

Records allow declaring multiple constructors with or without parameters as shown below:

记录允许声明带有或不带有参数的多个构造函数,如下所示:

record Author(String name, String topic) {
  public Author() {

    this("NA", "NA");
  }

  public Author(String name) {

    this(name, "NA");
  }
}

(4.4) Records Allow Modifying Accessor Methods)

Though records do generate public accessor methods for the fields defined in the state description, they also allow you to redefine the accessor methods in the body as shown below:

尽管记录确实会为状态描述中定义的字段生成公共访问器方法,但它们还允许您在主体中重新定义访问器方法,如下所示:

record Author(String name, String topic) {
  public String name() {
        return "This article was written by " + this.name;
    }
}

(4.5) Check Record and its Components at Runtime)

Records provide us with isRecord() and getRecordComponents() to check if the class is a record and also look into its fields and types. The following illustration shows how it is done:

记录为我们提供了isRecord()getRecordComponents()以检查该类是否为记录,并查看其字段和类型。 下图显示了它是如何完成的:


java 功能业务模块 java功能模块图_java 功能业务模块_05

Java 14 Records Runtime Check Java 14记录运行时检查

While we did add additional fields and methods to the record in the above code examples, make sure you don’t overdo this. Records are designed as plain data carriers and if you’re looking to implement a lot of additional methods, it’s better to fall back onto the normal class.

虽然我们确实在上述代码示例中向记录添加了其他字段和方法,但请确保不要过度使用。 记录被设计为普通的数据载体,如果您要实现许多其他方法,最好退回到普通类。

(5. Text Blocks (Preview))

Text Blocks were introduced as a preview feature in Java 13 with the goal to allow easy creation of multiline string literals. It’s useful in easily creating HTML and JSON or SQL query strings.

文本块是Java 13中的预览功能,其目的是允许轻松创建多行字符串文字。 在轻松创建HTML和JSON或SQL查询字符串时很有用。

In Java 14, Text Blocks are still in preview with some new additions. We can now use:

在Java 14中,文本块仍在预览中,并增加了一些新功能。 我们现在可以使用:

  • Backslash for displaying nice-looking multiline string blocks.
  • \s is used to consider trailing spaces which are by default ignored by the compiler. It preserves all the spaces present before it. \s用于考虑在编译器默认情况下会忽略的尾随空格。 它保留了前面的所有空间。
String text = """
                Did you know \
                Java 14 \
                has the most features among\
                all non-LTS versions so far\
                """;

String text2 = """
                line1
                line2 \s
                line3
                """;


String text3 = "line1\nline2 \nline3\n"

//text2 and text3 are equal.