|
| 1 | +import java.util.Map; |
| 2 | + |
| 3 | +public class JEP488PrimitiveTypesInPatternsInstanceofAndSwitch { |
| 4 | + public static void main(String[] args) { |
| 5 | + // JEP 488: Primitive Types in Patterns, instanceof, and switch (Second Preview) |
| 6 | + // https://openjdk.org/jeps/488 |
| 7 | + |
| 8 | + // Primitive Types ile Pattern Matching |
| 9 | + Object obj = 42; |
| 10 | + if (obj instanceof int i) { |
| 11 | + System.out.printf("Primitive int value: %1$s\n", i); |
| 12 | + } |
| 13 | + |
| 14 | + // Switch for Primitive Type |
| 15 | + System.out.printf("%1$s HTTP status code refers to a %2$s%n", 100, getHTTPCodeDesc(100)); |
| 16 | + System.out.printf("%1$s HTTP status code refers to a %2$s%n", 200, getHTTPCodeDesc(200)); |
| 17 | + System.out.printf("%1$s HTTP status code refers to a %2$s%n", 403, getHTTPCodeDesc(403)); |
| 18 | + System.out.printf("%1$s HTTP status code refers to a %2$s%n", 0, getHTTPCodeDesc(0)); |
| 19 | + |
| 20 | + // Record Patterns with Primitive Types |
| 21 | + JsonValue json = new JsonObject(Map.of( |
| 22 | + "name", new JsonString("Alice"), |
| 23 | + "age", new JsonNumber(28) |
| 24 | + )); |
| 25 | + |
| 26 | + if (json instanceof JsonObject(var map) |
| 27 | + && map.get("name") instanceof JsonString(var name) |
| 28 | + && map.get("age") instanceof JsonNumber(var age)) { |
| 29 | + System.out.printf("Name: %s, Age: %.0f%n", name, age); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // Switch for Primitive Type |
| 34 | + public static String getHTTPCodeDesc(int code){ |
| 35 | + return switch(code) { |
| 36 | + case 100 -> "Continue"; |
| 37 | + case 200 -> "OK"; |
| 38 | + case 301 -> "Moved Permanently"; |
| 39 | + case 302 -> "Found"; |
| 40 | + case 400 -> "Bad Request"; |
| 41 | + case 500 -> "Internal Server Error"; |
| 42 | + case 502 -> "Bad Gateway"; |
| 43 | + case int i when (i > 100 && i < 200) -> "Informational"; |
| 44 | + case int i when (i > 200 && i < 300) -> "Successful"; |
| 45 | + case int i when (i > 302 && i < 400) -> "Redirection"; |
| 46 | + case int i when (i > 400 && i < 500) -> "Client Error"; |
| 47 | + case int i when (i > 502 && i < 600) -> "Server Error"; |
| 48 | + default -> "Unknown error"; |
| 49 | + }; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +interface Human {} |
| 54 | +class Employee implements Human {} |
| 55 | +class Boss implements Human {} |
| 56 | + |
| 57 | +sealed interface JsonValue permits JsonString, JsonNumber, JsonObject {} |
| 58 | + |
| 59 | +record JsonString(String value) implements JsonValue {} |
| 60 | +record JsonNumber(double value) implements JsonValue {} |
| 61 | +record JsonObject(Map<String, JsonValue> map) implements JsonValue {} |
0 commit comments