目的:在调用被@Log
修饰的方法前先打印一行日志
1. 自定义一个Log注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Log { String operator() default "admin"; String ip() default "0.0.0.0"; char type(); }
|
2. Log注解处理器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.annotation;
import java.lang.reflect.Method;
public class ReflectProcessor {
public void parseAnnotation(final Class<?> clazz) throws Exception { final Object obj = clazz.getConstructor(new Class[]{}).newInstance(); final Method[] methods = clazz.getDeclaredMethods(); for (final Method method : methods) { final Log log = method.getAnnotation(Log.class); if (null != log) { System.out.printf("%s in %s execute %s\n", log.operator(), log.ip(), log.type()); method.invoke(obj, 18); } } } }
|
3. 测试
1 2 3 4 5 6 7
| public class ReflectTest {
public static void main(final String[] args) throws Exception { final ReflectProcessor reflectProcessor = new ReflectProcessor(); reflectProcessor.parseAnnotation(UserBiz.class); } }
|
4. 效果
1 2
| admin in 0.0.0.0 execute r query parameters age are 18
|
admin和0.0.0.0为注解默认值,r
为用户给注解赋的值