java 文本匹配_Java 15具有密封和隐藏类模式匹配和文本块的功能

java 文本匹配

Time seems to fly since the pandemic began in US and Europe in the middle of March, just around the time Java 14 got released, and now, six months of quarantine later, Java 15 is here!

自3月中旬在美国和欧洲开始大流行以来,时间似乎飞逝,就在Java 14发布之时,而现在,经过六个月的隔离,Java 15就在这里!

Fifteen is another feature release, and so will be 16, next LTS ( long term support release) is planned to be Java 17, which will release exactly one year from now, on September 2021.

第15个功能是另一个功能版本,第16个功能版本也将发布16个功能,下一个LTS(长期支持版本)计划是Java 17,它将从现在起一年后的2021年9月发布。

This release brings us new preview feature like Sealed Classes, next we have second previews of Records and Pattern Matching for instanceof. And of course we have ready to use, out of preview, Text Blocks and Hidden Classes.

此版本为我们带来了新的预览功能,例如Sealed Classes,接下来是instanceof的Records和Pattern Matching的第二个预览。 当然,我们已经准备好在预览版之外使用文本块和隐藏类。

I wrote about Text Blocks about one year ago in my Java 13 blog, when they were new preview feature, over the last two release they were battle tested, Java team took all the feedback from the community and now they are finally production ready.

大约一年前,我在Java 13博客中撰写了有关Text Blocks的文章 ,当时它们是新的预览功能,在过去的两个发行版中,它们经过了实战测试,Java团队从社区中吸收了所有反馈,现在终于可以投入生产了。

Let’s start by looking at the new preview feature!

让我们先来看一下新的预览功能!

密封类 (Sealed Classes)

This is a great change, and finally one of the problems Java had from the 1.0 version 25 years ago is now getting addressed.

这是一个巨大的变化,并且终于解决了Java在25年前的1.0版本中遇到的问题之一。

A common process we have when creating new classes and interfaces is deciding which scope modifier should we use, it’s always case by case and until now the options language was providing weren’t granular enough.

创建新类和接口时,我们有一个常见的过程是确定应使用哪个范围修饰符,这种情况总是逐案的,直到现在提供的选项语言还不够细致。

This issue is way more prevalent when you have a project where using default (package-private) scope modifier is not encouraged by the official style guide. I have that situation currently on my project and making class (that needs to be inherited at some point) either public or protected is sometimes just too generous.

当您有一个项目使用官方样式指南不鼓励使用默认(package-private)作用域修饰符时,此问题会更加普遍。 我目前在我的项目中遇到这种情况,并且使类(需要在某个时刻继承)公开或受保护有时太慷慨了。

With Java 15 that issue is solved and now we have fine grained inheritance control using sealed scope modifier for classes and interfaces.

使用Java 15可以解决此问题,现在我们可以使用sealed作用域修饰符对类和接口进行细粒度的继承控制。

So if you need your super class to be widely accessible but not arbitrary extensible, sealed modifier is your friend.

因此,如果您需要您的超类可以被广泛访问但不能任意扩展,则密封修饰符是您的朋友。

Example from the JDK documentation:

来自JDK文档的示例:

package com.example.geometry;
public sealed class Shapepermits Circle, Rectangle, Square {...}

If you have nested classes or more that one class in the same source file you can omit permits for those classes, Java compiler will infer permitted subclasses as long as they are in the same file.

如果在同一源文件中嵌套的类或一个以上的类可以忽略这些类的permits ,则Java编译器将推断允许的子类,只要它们在同一文件中即可。

That means in the example above, as long as Shape, Circle, Rectangle and Square are in the same source file you can omit permits and your code can look something like this:

这意味着在上面的示例中,只要Shape,Circle,Rectangle和Square位于同一源文件中,您可以省略permits并且代码可以如下所示:

package com.example.geometry;sealed class Shape {...}
... class Circle extends Shape {...}
... class Rectangle extends Shape {...}
... class Square extends Shape {...}

This might be a rear case, but if you want to save a few bytes by not writing permits in an example above you can do it, compiler will know what to do.

可能是后一种情况,但是如果您想通过在上面的示例中不写permits来节省一些字节,则可以这样做,编译器将知道该怎么做。

Permitted classes can be final , sealed or non-sealed.

允许的课程可以是finalsealed non-sealed

package com.example.geometry;
public sealed class Shapepermits Circle, Rectangle, Square {...}
public final class Circle extends Shape {...}
public sealed class Rectangle extends Shape permits TransparentRectangle, FilledRectangle {...}
public final class TransparentRectangle extends Rectangle {...}
public final class FilledRectangle extends Rectangle {...}
public non-sealed class Square extends Shape {...}

Final will prevent its part of the class hierarchy from being extended further.

Final将阻止其在类层次结构中的进一步扩展。

Sealed will allow its part of the hierarchy to be extended further than super class originally defined, but only by classes that sealed subclass permits.

密封将允许其层次结构的一部分扩展到比最初定义的超类更大的范围,但仅限于密封子类允许的类。

And finally non-sealed will return things back in to the wild and revert the class hierarchy to being open for extension by unknown sub classes, off course starting from the child non-sealed class, super class is still sealed so it’s still off limits for unknown extension.

最终, non-sealed将使事情重新回到野外,并将类层次结构还原为由未知子类开放以进行扩展,当然,从子非密封类开始,超级类仍处于密封状态,因此它仍然不受限制扩展名未知。

On that note, non-sealed is (I believe) first keyword in Java that has a hyphen, i don’t know why they introduced this inconsistency to the language, there are already two-word keywords, like instanceof, and they don’t use hyphen, so I think that they should have stayed consistent and used nonsealed

关于这一点,(我相信) non-sealed是Java中带有连字符的第一个关键字,我不知道为什么他们在语言中引入了这种不一致,已经有两个单词的关键字,例如instanceof,而它们却没有。不要使用连字符,因此我认为它们应保持一致并使用非nonsealed

Java’s Reflection API was also extended to add support for sealed classes, there are two new methods, both pretty self explanatory:

Java的Reflection API也进行了扩展,以增加对密封类的支持,其中有两种新方法,两种方法都很容易解释:

java.lang.constant.ClassDesc[] getPermittedSubclasses();boolean isSealed()

You should keep a close eye on sealed classes / interfaces feature because in one of the future Java releases this will work great for pattern matching in switch expressions.

您应该密切注意密封的类/接口功能,因为在将来的Java版本中,这将非常适合开关表达式中的模式匹配。

隐藏的课程 (Hidden Classes)

Hidden classes is a feature that’s most interesting to framework developers.

隐藏类是框架开发人员最感兴趣的功能。

It allows them to create classes that cannot be used directly by the bytecode of other classes, they are intended for use by the framework itself that generate classes at run time and use them indirectly, via reflection.

它允许他们创建不能被其他类的字节码直接使用的类,它们供框架本身使用,这些框架本身在运行时生成类并通过反射间接使用它们。

For the full motivation behind this feature your can read open JDK docs, but here is the gist of it.

要获得此功能背后的全部动力,您可以阅读开放的JDK文档 ,但这是要点。

Standard APIs that define a class ClassLoader::defineClass and Lookup::defineClass are indifferent to whether the bytecodes of the class were generated dynamically (at run time) or statically (at compile time). These APIs always define a visible class that will be used every time another class in the same loader hierarchy tries to link a class of that name.

定义类ClassLoader:: defineClassLookup:: defineClass标准API无关紧要是动态(在运行时)还是静态(在编译时)生成该类的字节码。 这些API始终定义一个可见的类,该类将在每次在同一加载器层次结构中的另一个类尝试链接该名称的类时使用

So, If a standard API could define hidden classes that are not discoverable and have a limited lifecycle, then frameworks both inside and outside of the JDK that generate classes dynamically could instead define hidden classes, that have way lower visibility and overhead, which would improve the efficiency of all language implementations built on the JVM.

因此,如果标准API可以定义无法发现且具有有限生命周期的隐藏类,则动态生成类的JDK内部和外部框架可以改为定义隐藏类,从而降低可见性和开销,这将改善基于JVM的所有语言实现的效率。

Adding this feature also allows deprecation of non-standard API sun.misc.Unsafe::defineAnonymousClass . Hidden classes will not support every functionality that defineAnonymousClass does, and that’s not the goal here, but the goal is to deprecate that API and to fully remove it in upcoming releases.

添加此功能还可以弃用非标准API sun.misc.Unsafe:: defineAnonymousClass 。 隐藏的类将不支持defineAnonymousClass支持的所有功能,这不是这里的目标,但是目标是不赞成该API,并在即将发布的版本中将其完全删除。

We will not go any deeper into hidden classes, since this is mostly applicable for framework developers working on low level internal stuff, all other info on this can be found in official JEP.

我们不会更深入地介绍隐藏类,因为这主要适用于从事底层内部工作的框架开发人员,有关此问题的所有其他信息,请参见官方JEP

instanceof的模式匹配(第二预览) (Pattern Matching for instanceof (Second Preview))

This was introduced originally as a preview feature in Java 14. The second preview in Java 15 doesn’t have any new changes, the feature is the same as it was introduced in Java 14.

它最初是作为Java 14中的预览功能引入的。Java15中的第二个预览没有任何新更改,该功能与Java 14中引入的功能相同。

The main goal of this re-preview is to get more feedback from the community.

重新预览的主要目的是从社区中获得更多反馈。

We are all familiar with instanceof-and-cast idiom, it’s widely used across all bigger code bases:

我们都熟悉instanceof-and-cast惯用语,它已在所有较大的代码库中广泛使用:

if (obj instanceof String) {
String s = (String) obj;
s.contains("Java 13");
} else {
...
}

Pattern Matching for instanceof gives as a cleaner way to do this check, the instanceof operator is now extended to take a type test pattern instead of just a type:

对instanceof进行模式匹配提供了一种更干净的方法来执行此检查,现在将instanceof运算符扩展为采用类型测试模式,而不仅仅是类型:

if (obj instanceof String s) {s.contains("Java 15 with Pattern Matching");
} else {
...
}

No need for the explicit casting in the true block, it’s less code than before and it’s more readable.

不需要在true块中进行显式强制转换,它的代码比以前更少了,并且更具可读性。

记录(第二预览) (Records (Second Preview))

Records were introduced as preview feature in Java 14.

记录是Java 14中的预览功能。

This is a re-preview that contains changes based on community feedback from prior (Java 14's) preview.

这是一个重新预览,其中包含基于先前(Java 14的)预览中社区反馈的更改。

The ultimate goal of records is to enable developers to, easier than before, create immutable, data-driven constructs in Java.

记录的最终目标是使开发人员能够比以前更轻松地用Java创建不可变的,数据驱动的构造。

Records are a new kind of class whose declaration consists of a name, header and a body. The header lists the components of the record, which are the variables that make up its state.

记录是一种新型的类,其声明由名称,标题和主体组成。 标头列出了记录的组成部分,它们是构成其状态的变量。

record Point(int x, int y) { }

All variables, in this case x and y will automatically have a public accessor with the same name and return type as that variable.

所有变量(在本例中为xy将自动具有与该变量相同名称和返回类型的公共访问器。

In the body of the record you can add arbitrary methods that operate on records state.

在记录的主体中,您可以添加对记录状态进行操作的任意方法。

Reflection API was updated, so you can operate with record type classes:

Reflection API已更新,因此您可以使用记录类型类:

// return all variables from the header
RecordComponent[] getRecordComponents();// is given class declared as a record
boolean isRecord();

Records are a clean way of creating a data class in Java with handful of lines of code. All records are final, they can’t play the inheritance game.

记录是用几行代码在Java中创建数据类的一种干净方法。 所有记录都是最终的,它们不能玩继承游戏。

文字块 (Text Blocks)

What started as a preview way back in Java 12 is now permanent feature!

从Java 12的预览方式开始,现在已成为永久功能!

Text blocks allow a better way of writing, and more importantly reading, multi-line text inside Java code. This was longed for in Java, especially because other languages that run on Java virtual machines, like Kotlin and Scala, have had support for multi-line text for quite some time now.

文本块提供了更好的书写方式,更重要的是,可以读取Java代码中的多行文本。 这是Java所渴望的,尤其是因为在Java虚拟机上运行的其他语言(例如KotlinScala )已经支持多行文本已有相当长的一段时间了。

The main problem text blocks solve is writing code from other languages inside your Java code. Previously, you would always need boilerplate like /n for line breaks at the end of every line, which makes code error-prone and hard to read.

文本块解决的主要问题是在Java代码中编写其他语言的代码。 以前,您总是需要像/n这样的样板才能在每一行的末尾使用换行符,这使得代码易于出错且难以阅读。

Text blocks give you a better way to write multi-line text in Java. They use triple quotation marks as delimiters and can be used anywhere regular string can.

文本块为您提供了一种更好的用Java编写多行文本的方法。 它们使用三引号作为分隔符,并且可以在常规字符串可以使用的任何地方使用。

// SQL example// Using "one-dimensional" string literals
String query =
"SELECT \"EMP_ID\", \"LAST_NAME\" FROM \"EMPLOYEE_TB\"\n" +
"WHERE \"CITY\" = 'INDIANAPOLIS'\n" +
"ORDER BY \"EMP_ID\", \"LAST_NAME\";\n";// Using a "two-dimensional" block of text
String query = """
SELECT "EMP_ID", "LAST_NAME" FROM "EMPLOYEE_TB"
WHERE "CITY" = 'INDIANAPOLIS'
ORDER BY "EMP_ID", "LAST_NAME";
""";

Note that text blocks cannot be used on a single line: opening quotes must be followed by a line terminator or code will not compile.

请注意,文本块不能在单行上使用:引号引起来的必须是行终止符,否则代码将无法编译。

The Java compiler will compile Text Block into regular string and there will be no hints if it was originally string or text block.

Java编译器会将“文本块”编译为常规字符串,如果它最初是字符串或文本块,则没有任何提示。

Pretty great features, right?

很棒的功能,对不对?

Java is heading full speed on with this six month release schedule, with 15 barely being out, I already want to discus what will 16 and next LTS 17 bring to the table. Great time to write Java code!

Java计划在六个月的发布计划中全力以赴,只有15个即将发布,我已经想讨论16和下一个LTS 17将带来什​​么。 编写Java代码的好时机!

You can read full release notes and try JDK 15 yourself on their official website.

您可以阅读完整的发行说明,并在其官方网站上尝试JDK 15。

翻译自: https://medium.com/better-programming/java-15-features-sealed-and-hidden-classes-pattern-matching-and-text-blocks-38f4efdc8adc

java 文本匹配

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值