java功能模块





Java 13 was released for production use on 17th September 2019. There are not a lot of developer-specific features in Java 13 because of the 6-month release cycle.

Java 13已于2019年9月17日发布供生产使用。由于6个月的发布周期,Java 13中没有很多针对开发人员的功能。

(Java 13 Features)

Some of the important Java 13 features are:

Java 13的一些重要功能包括:





  • Text Blocks – JEP 355
  • New Methods in String Class for Text Blocks
  • Switch Expressions Enhancements – JEP 354
  • Reimplement the Legacy Socket API – JEP 353
  • Dynamic CDS Archive – JEP 350
  • ZGC: Uncommit Unused Memory – JEP 351
  • FileSystems.newFileSystem() Method
  • Support for Unicode 12.1
  • DOM and SAX Factories with Namespace Support

(How to Enable Preview Features)

Switch expressions and text blocks are preview features. So you will have to enable the preview-feature settings in your project.

开关表达式和文本块是预览功能。 因此,您将必须在项目中启用预览功能设置。

If you are running a java program from the command line, you can enable it using the --enable-preview switch. You can use this switch to start JShell with preview features enabled.

如果您从命令行运行Java程序,则可以使用--enable-preview开关启用它。 您可以使用此开关在启用预览功能的情况下启动JShell。

$ jshell --enable-preview

$ java --enable-preview --source 13 Test.java

If you are using Eclipse IDE, you can enable the preview features from the project Java Compiler settings.

如果使用的是Eclipse IDE,则可以从项目Java编译器设置中启用预览功能。




java 部门模块 java功能模块_java

Eclipse Enable Preview Features

Eclipse启用预览功能





(1. Text Blocks – JEP 355)

This is a preview feature. It allows us to create multiline strings easily. The multiline string has to be written inside a pair of triple-double quotes.

这是预览功能。 它使我们可以轻松地创建多行字符串。 多行字符串必须写在一对三重双引号内。

The string object created using text blocks has no additional properties. It’s an easier way to create multiline strings. We can’t use text blocks to create a single-line string.

使用文本块创建的字符串对象没有其他属性。 这是一种创建多行字符串的简便方法。 我们不能使用文本块来创建单行字符串。

The opening triple-double quotes must be followed by a line terminator.

开头的三重双引号后必须跟一个行终止符。

package com.journaldev.java13.examples;

public class TextBlockString {

	/**
	 * JEP 355: Preview Feature
	 */
	@SuppressWarnings("preview")
	public static void main(String[] args) {
		String textBlock = """
				Hi
				Hello
				Yes""";

		String str = "Hi\nHello\nYes";

		System.out.println("Text Block String:\n" + textBlock);
		System.out.println("Normal String Literal:\n" + str);

		System.out.println("Text Block and String Literal equals() Comparison: " + (textBlock.equals(str)));
		System.out.println("Text Block and String Literal == Comparison: " + (textBlock == str));
	}

}

Output:

输出:

Text Block String:
Hi
Hello
Yes
Normal String Literal:
Hi
Hello
Yes
Text Block and String Literal equals() Comparison: true
Text Block and String Literal == Comparison: true

It’s useful in easily creating HTML and JSON strings in our Java program.

在我们的Java程序中轻松创建HTML和JSON字符串很有用。





String textBlockHTML = """
		<html>
		<head>
			<link href='/css/style.css' rel='stylesheet' />
		</head>
		<body>
                        <h1>Hello World</h1>
                </body>
                </html>""";

String textBlockJSON = """
		{
			"name":"Pankaj",
			"website":"JournalDev"
		}""";

(2. New Methods in String Class for Text Blocks)

There are three new methods in the String class, associated with the text blocks feature.

String类中有三个与文本块功能关联的新方法。

  1. formatted(Object… args): it’s similar to the String format() method. It’s added to support formatting with the text blocks.
  2. stripIndent(): used to remove the incidental white space characters from the beginning and end of every line in the text block. This method is used by the text blocks and it preserves the relative indentation of the content.
  3. translateEscapes(): returns a string whose value is this string, with escape sequences translated as if in a string literal.
package com.journaldev.java13.examples;

public class StringNewMethods {

	/***
	 * New methods are to be used with Text Block Strings
	 * @param args
	 */
	@SuppressWarnings("preview")
	public static void main(String[] args) {
		
		String output = """
			    Name: %s
			    Phone: %d
			    Salary: $%.2f
			    """.formatted("Pankaj", 123456789, 2000.5555);
		
		System.out.println(output);
		
		
		String htmlTextBlock = "<html>   \n"+
				                    "\t<body>\t\t \n"+
				                        "\t\t<p>Hello</p>  \t \n"+
				                    "\t</body> \n"+
				                "</html>";
		System.out.println(htmlTextBlock.replace(" ", "*"));
		System.out.println(htmlTextBlock.stripIndent().replace(" ", "*"));
		
		String str1 = "Hi\t\nHello' \" /u0022 Pankaj\r";
		System.out.println(str1);
		System.out.println(str1.translateEscapes());
		
	}

}

Output:

输出:

Name: Pankaj
Phone: 123456789
Salary: $2000.56

<html>***
	<body>		*
		<p>Hello</p>**	*
	</body>*
</html>
<html>
	<body>
		<p>Hello</p>
	</body>
</html>
Hi	
Hello' " /u0022 Pankaj
Hi	
Hello' " /u0022 Pankaj

(3. Switch Expressions Enhancements – JEP 354)

Switch expressions were added as a preview feature in Java 12 release. It’s almost same in Java 13 except that the “break” has been replaced with “yield” to return a value from the case statement.

开关表达式已添加为Java 12版本中的预览功能。 在Java 13中几乎一样,只是“ break”已替换为“ yield”以从case语句返回值。

package com.journaldev.java13.examples;

/**
 * JEP 354: Switch Expressions
 * https://openjdk.java.net/jeps/354
 * @author pankaj
 *
 */
public class SwitchEnhancements {

	@SuppressWarnings("preview")
	public static void main(String[] args) {
		int choice = 2;

		switch (choice) {
		case 1:
			System.out.println(choice);
			break;
		case 2:
			System.out.println(choice);
			break;
		case 3:
			System.out.println(choice);
			break;
		default:
			System.out.println("integer is greater than 3");
		}

		// from java 13 onwards - multi-label case statements
		switch (choice) {
		case 1, 2, 3:
			System.out.println(choice);
			break;
		default:
			System.out.println("integer is greater than 3");
		}

		// switch expressions, use yield to return, in Java 12 it was break
		int x = switch (choice) {
		case 1, 2, 3:
			yield choice;
		default:
			yield -1;
		};
		System.out.println("x = " + x);

	}

	enum Day {
		SUN, MON, TUE
	};

	@SuppressWarnings("preview")
	public String getDay(Day d) {
		String day = switch (d) {
		case SUN -> "Sunday";
		case MON -> "Monday";
		case TUE -> "Tuesday";
		};
		return day;
	}
}

(4. Reimplement the Legacy Socket API – JEP 353)

The underlying implementation of the java.net.Socket and java.net.ServerSocket APIs have been rewritten. The new implementation, NioSocketImpl, is a drop-in replacement for PlainSocketImpl.

java.net.Socket和java.net.ServerSocket API的基础实现已被重写。 新的实现NioSocketImpl替代了PlainSocketImpl。

It uses java.util.concurrent locks rather than synchronized methods. If you want to use the legacy implementation, use the java option -Djdk.net.usePlainSocketImpl.

它使用java.util.concurrent锁而不是同步方法。 如果要使用旧版实现,请使用java选项-Djdk.net.usePlainSocketImpl

(5. Dynamic CDS Archive – JEP 350)

This JEP extends the class-data sharing feature, which was introduced in Java 10. Now, the creation of CDS archive and using it is much easier.

该JEP扩展了Java 10中引入的类数据共享功能。 现在,创建CDS存档并使用它要容易得多。

$ java -XX:ArchiveClassesAtExit=my_app_cds.jsa -cp my_app.jar

$ java -XX:SharedArchiveFile=my_app_cds.jsa -cp my_app.jar

(6. ZGC: Uncommit Unused Memory – JEP 351)

This JEP has enhanced ZGC to return unused heap memory to the operating system. The Z Garbage Collector was introduced in Java 11. It adds a short pause time before the heap memory cleanup. But, the unused memory was not being returned to the operating system. This was a concern for devices with small memory footprint such as IoT and microchips. Now, it has been enhanced to return the unused memory to the operating system.

该JEP增强了ZGC,可以将未使用的堆内存返回给操作系统。 Z垃圾收集器是Java 11中引入的。 它会在堆内存清理之前增加短暂的暂停时间。 但是,未使用的内存没有返回给操作系统。 对于诸如IoT和微芯片等内存占用较小的设备,这是一个问题。 现在,它已得到增强,可以将未使用的内存返回给操作系统。

(7. FileSystems.newFileSystem() Method)

Three new methods have been added to the FileSystems class to make it easier to use file system providers, which treats the contents of a file as a file system.

已将三个新方法添加到FileSystems类中,以使其更易于使用文件系统提供程序,该系统将文件的内容视为文件系统。

  1. newFileSystem(Path)
  2. newFileSystem(Path, Map<String, ?>)
  3. newFileSystem(Path, Map<String, ?>, ClassLoader)

(8. DOM and SAX Factories with Namespace Support)

There are new methods to instantiate DOM and SAX factories with Namespace support.

有支持命名空间的实例化DOM和SAX工厂的新方法。

  1. newDefaultNSInstance()
  2. newNSInstance()

//java 13 onwards
DocumentBuilder db = DocumentBuilderFactory.newDefaultNSInstance().newDocumentBuilder(); 

// before java 13
DocumentBuilderFactory dbf = DocumentBuilderFactory.newDefaultInstance(); 
dbf.setNamespaceAware(true); 
DocumentBuilder db = dbf.newDocumentBuilder();

(Conclusion)

It looks like that the 6-months release of Java has been working well. There are not many developer-specific features, but overall it’s a great release. It’s good to see the much-awaited text blocks string support.

Java的6个月发行版似乎运行良好。 没有很多特定于开发人员的功能,但是总体而言,这是一个不错的版本。 很高兴看到期待已久的文本块字符串支持。