Pencocokan pola di Jawa: InstanceOf (JEP 305)

Pencocokan Pola adalah fitur pratinjau baru di Java 14.


contoh


Untuk lebih memahami fitur baru ini, mari kita lihat bagaimana instanceof bekerja . Jika Anda sudah terbiasa dengan itu, jangan ragu untuk pindah ke bagian selanjutnya.


Singkatnya, ia memeriksa untuk melihat apakah objek yang diberikan milik tipe tertentu. Sebagai hasil dari pemeriksaan ini, ia mengembalikan benar atau salah .


    if(animal instanceof Cat) {
      // It is a cat! Do something
    } else {
      // It is not a cat, do something 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, , :


  1. -, , animal , instanceof.
  2. Cat Dog.
  3. animal .

Cat Dog. .


, . . , , Cat Dog.


, Java 14 instanceof, JEP 305. , .



Java 14 .


// Before Java 14
if(animal instanceof Cat) {
    Cat cat = (Cat)animal;
    return cat.meow();
}

//After
if(animal instanceof Cat cat) {
    return cat.meow();
}

:


  1. cat, .
  2. . cat, Cat.
  3. cat if.

, , .



, if:


if(animal instanceof Cat cat) {
    return cat.meow();
} else {
    // Can't use cat here
}
// Can't use cat here either

, 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


Rekaman
Ditingkatkan Beralih
Blok Teks


All Articles