-
Notifications
You must be signed in to change notification settings - Fork 0
/
Example4.java
executable file
·51 lines (40 loc) · 1.38 KB
/
Example4.java
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
package com.github.forax.virtualbean.example;
import com.github.forax.virtualbean.BeanFactory;
import com.github.forax.virtualbean.BeanFactory.Advice;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
/**
* Dynamically register/unregister a logger to log enter and exit of a method
*/
public class Example4 {
@Retention(RetentionPolicy.RUNTIME)
@interface Log { }
public static void main(String[] args) {
var lookup = MethodHandles.lookup();
var beanFactory = new BeanFactory(lookup);
var interceptor = new Advice() {
@Override
public void pre(Method method, Object bean, Object[] args) {
System.out.println("enter " + method);
}
@Override
public void post(Method method, Object bean, Object[] args) {
System.out.println("exit " + method);
}
}.asInterceptor();
interface HelloManager {
@Log
default void sayHello(String text) {
System.out.println("hello " + text);
}
}
var helloManager = beanFactory.create(HelloManager.class);
helloManager.sayHello("no log");
beanFactory.registerInterceptor(Log.class, interceptor);
helloManager.sayHello("with log");
beanFactory.unregisterInterceptor(Log.class, interceptor);
helloManager.sayHello("with no log anymore");
}
}