java利用@interface定义元注解及使用实例

来源:互联网 发布:唱歌录音软件 编辑:程序博客网 时间:2024/06/10 21:54

项目中遇到一个日志记录功能,记录登录系统用户的行为日志(对订单进行验单,发货,退款等操作)。使用了拦截器及注解的形式,来完成日志记录。
参考网络资源,写一个简单的demo,对java元注解知识进行一个梳理
demo资源目录结构如下:
demo资源目录接口预览
1、利用@interface定义日志记录注解

package com.sunny.core.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * Created by Administrator on 2017/3/16. */@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface LogRecord {    public String id();    public String description() default  "no description";}

2、新建密码工具类,使用日志记录注解
package com.sunny.core.annotation;

import org.apache.poi.ss.formula.functions.T;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
*
* Created by Administrator on 2017/3/16.
*/
public class PasswordUtil {

/** * 密码校验 * @param password * @return */@LogRecord(id="47",description = "Passwords must contain at least one numeric")public boolean validatePassword(String password){    return (password.matches("\\w*\\d\\w*"));}/** * 对字符串序列进行反转加密 * @param password * @return */@LogRecord(id="48")public String encryptPassword(String password){    return  new StringBuilder(password).reverse().toString();}

}

3、新建测试类
package com.sunny.core.annotation;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
* Created by Administrator on 2017/3/16.
*/
public class PasswordUtilTest {

public static void main(String[] args) {    List<Integer> logIds=new ArrayList<Integer>();    Collections.addAll(logIds, 47, 48, 49, 50);    trackLogRecord(logIds,PasswordUtil.class);}/** * 追踪日志记录 */public static void  trackLogRecord(List<Integer> logIds,Class<?> cl){    for (Method method:cl.getDeclaredMethods()) {        LogRecord logRecord = method.getAnnotation(LogRecord.class);        if(logRecord!=null){            System.out.println("Found LogRecord:"+logRecord.id()+" "+logRecord.description());            logIds.remove(new Integer(logRecord.id()));        }    }    for(int logId:logIds){        System.out.println("Warning:Missing LogRecord ,Id:"+logId);    }}

}

4、运行测试类,输出测试情况
这里写图片描述

参考资料:http://www.cnblogs.com/pepcod/archive/2013/02/16/2913474.html

0 0
原创粉丝点击