Pattern Matching ist eine neue Vorschaufunktion in Java 14.

Instanz von
Um diese neue Funktion besser zu verstehen, sehen wir uns an, wie die Instanz des Operators funktioniert . Wenn Sie bereits damit vertraut sind, können Sie mit dem nächsten Abschnitt fortfahren.
Kurz gesagt, es wird geprüft, ob ein bestimmtes Objekt zu einem bestimmten Typ gehört. Als Ergebnis dieser Überprüfung wird entweder true oder false zurückgegeben .
if(animal instanceof Cat) {
} else {
}
true, . false.
instanceof
. Animal — , : Cat Dog.
public String getAnimalSound(Animal animal) {
if(animal instanceof Cat) {
Cat cat = (Cat)animal;
return cat.meow();
} else if (animal instanceof Dog) {
Dog dog = (Dog)animal;
return dog.bark();
}
throw new UnknownAnimalException();
}
animal . animal Cat, , «». Dog, . Animal, , :
- -, , animal , instanceof.
- Cat Dog.
- animal .
Cat Dog. .
, . . , , Cat Dog.
, Java 14 instanceof, JEP 305. , .
Java 14 .
if(animal instanceof Cat) {
Cat cat = (Cat)animal;
return cat.meow();
}
if(animal instanceof Cat cat) {
return cat.meow();
}
:
- cat, .
- . cat, Cat.
- cat if.
, , .
, if:
if(animal instanceof Cat cat) {
return cat.meow();
} else {
}
, if, , AND/OR.
if(animal instanceof Cat cat && cat.isAlive()) {
return cat.meow();
}
instanceof, &&, cat, Cat, Animal.
IDEA
, IntelliJ IDEA , 2020.1 ( Java 14, Records Switch).

!
, JDK 14.
instanceof Java 14. (Preview feature). ?
VM — Java SE, , , . JDK ; , Java SE.
JDK , , Java SE , , . , ( ), ( ), .
JDK, . . , , , .
IntelliJ IDEA
IntelliJ IDEA File → Project Structure.

, , javac:
javac --release 14 --enable-preview ...
. --enable-preview
java --enable-preview ...
Maven
Maven :
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<release>14</release>
<compilerArgs>
--enable-preview
</compilerArgs>
```14</source>
<target>14</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
Java 14
Zeichnet
erweiterte Switch-
Textblöcke auf