1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
package de.wenzlaff.twrente; import java.math.BigDecimal; /** * Verwendung von Record Patterns beim Pattern Matching. * * Mit JEP 440 in Java 21 eingeführt * * @author Thomas Wenzlaff */ public class StartJava21 { // Records sind Klassen mit einer neuen kompakten Schreibweise zum Halten von unveränderlichen Daten. // Können übrigens mittels Jackson direkt geparst und gleichzeitig per Annotation validiert werden. // Instanziert wird ein neuer Record immer mit dem Konstruktor, der alle Argumente enthält. // Dieser Konstruktor ergibt sich bereits aus der Record Definition. record Point(int x, int y) {} record Info(String thema) {} record Mindmap(String name, Long id, String thema) {}; record ParameterObjekt(int id, BigDecimal währung, Long ziel) { // default Konstruktor für währung und ziel public ParameterObjekt(int id) { this(id,BigDecimal.TEN, Long.MIN_VALUE); }}; public static void main(String[] args) { Object obj = new Point(3, 4); if (obj instanceof Point(int x, int y)) { System.out.println("x=" + x + ", y=" + y + " Summe=" + (x + y)); // Achtung, ohne Klammern: System.out.println("x=" + x + ", y=" + y + " Summe=" + x + y); // = 34 ! } // erzeugt automatisch: // Getter Methoden ... // equals Methode ... // hashCode Methode ... // toString Methode ... Info i = new Info("Attributnamen ohne get also i.thema statt i.getThema"); System.out.println("Info: " + i.thema + " und toString: " + i.toString()); // Info[thema=Attributnamen ohne get also i.thema statt i.getThema] System.out.println("hashCode: " + i.hashCode()); // -702758727 System.out.println("equals: " + i.equals(i)); // true System.out.println("equals Info - Point: " + i.equals(obj)); // false System.err.println("Keine setThema, da nicht veränderbar"); ParameterObjekt btc = new ParameterObjekt(5, BigDecimal.ONE, Long.MAX_VALUE); System.out.println("Betrag: " + btc.währung); // 1 ParameterObjekt btcDefault = new ParameterObjekt(2); System.out.println("Default Betrag: " + btcDefault.währung); // 10 } } |