blob: 5ca2b9611d93091c51e8210e255662f27639d5c6 (
plain)
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
62
63
64
65
|
aspect SwitchPatternAspect {
Object around(Object o) : execution(* doSomethingWithObject(*)) && args(o) {
System.out.println(switch (o) {
case null -> "null";
case Integer i -> String.format("int %d", i);
case Long l -> String.format("long %d", l);
case Double d -> String.format("double %f", d);
case String s -> String.format("String %s", s);
default -> o.toString();
});
return proceed(o);
}
before(Shape s) : execution(* doSomethingWithShape(*)) && args(s) {
System.out.println(switch (s) {
case Circle c && (c.calculateArea() > 100) -> "Large circle";
case Circle c -> "Small circle";
default -> "Non-circle";
});
}
after(S s) : execution(* doSomethingWithSealedClass(*)) && args(s) {
System.out.println(switch (s) {
case A a -> "Sealed sub-class A";
case B b -> "Sealed sub-class B";
case C c -> "Sealed sub-record C";
});
}
}
class Shape {}
class Rectangle extends Shape {}
class Circle extends Shape {
private final double radius;
public Circle(double radius) { this.radius = radius; }
double calculateArea() { return Math.PI * radius * radius; }
}
sealed interface S permits A, B, C {}
final class A implements S {}
final class B implements S {}
record C(int i) implements S {} // Implicitly final
public class Application {
public static void main(String[] args) {
doSomethingWithObject(null);
doSomethingWithObject(123);
doSomethingWithObject(999L);
doSomethingWithObject(12.34);
doSomethingWithObject("foo");
doSomethingWithObject(List.of(123, "foo", 999L, 12.34));
doSomethingWithShape(new Rectangle());
doSomethingWithShape(new Circle(5));
doSomethingWithShape(new Circle(6));
doSomethingWithSealedClass(new A()));
doSomethingWithSealedClass(new B()));
doSomethingWithSealedClass(new C(5)));
}
public Object doSomethingWithObject(Object o) { return o; }
public void doSomethingWithSealedClass(S s) {}
public void doSomethingWithShape(Shape s) {}
}
|