Java注解@interface(入门)

本文转载自:http://blog.csdn.net/itzyjr/article/details/42875347

    注解(也被称为元数据)为我们在代码中添加信息提供了一种形式化的方法,使我们可以在稍后某个时刻非常方便地使用这些数据。


——————————————————————————————————————–


1.定义注解:

package com.test;  

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 UseCase {  
    public int id();  
    public String description() default "no description";  
}  

2.在下面的类中,有三个方法被注解为用例:

package com.test;  

import java.util.List;  

public class PasswordUtils {  
    @UseCase(id = 47, description = "Passwords must contain at lease one numeric")  
    public boolean validatePassword(String password) {  
        return password.matches("\\w*\\d\\w*");  
    }  

    @UseCase(id = 48)  
    public String encryptPassword(String password) {  
        return new StringBuilder(password).reverse().toString();  
    }  

    @UseCase(id = 49, description = "New password can't equal previously used ones")  
    public boolean checkForNewPassword(List<String> prevPasswords, String password) {  
        return !prevPasswords.contains(password);  
    }  
} 

3.编写注解处理器:

package com.test;  

import java.lang.reflect.*;  
import java.util.*;  

public class UseCaseTracker {  
    public static void trackUseCases(List<Integer> useCases, Class<?> cl) {  
        for (Method m : cl.getDeclaredMethods()) {  
            UseCase uc = m.getAnnotation(UseCase.class);  
            if (uc != null) {  
                System.out.println("Found Use Case:" + uc.id() + " " + uc.description());  
                useCases.remove(new Integer(uc.id()));  
            }  
        }  
        for (int i : useCases) {  
            System.out.println("Warning: Missing use case-" + i);  
        }  
    }  

    public static void main(String[] args) {  
        List<Integer> useCases = new ArrayList<Integer>();  
        Collections.addAll(useCases, 47, 48, 49, 50);  
        trackUseCases(useCases, PasswordUtils.class);  
    }  
}  

输出:

Found Use Case:49 New password can’t equal previously used ones
Found Use Case:47 Passwords must contain at lease one numeric
Found Use Case:48 no description
Warning: Missing use case-50

另外一篇参考:http://blog.csdn.net/liuwenbo0920/article/details/7290586

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值