Annotation 使用笔记(一)

简述:

《Java 编程思想第四版 》 第20章注解使用笔记


1. 用自定义注解,注解方法

CustomizedAnnotation.java

package com.anialy.test.annotation;

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

TestBean.java

package com.anialy.test.annotation;

public class TestBean {
	@CustomizedAnnotation(id = 1, description = "test function !")
	public void voidFunc(){};
	
	@CustomizedAnnotation(id = 3)
	public String stringFunc(){
		return "I'm String";
	};
}

CustomizedAnnotationTracker.java 用来表示调用的Bean中哪个id的注解遗漏了(可以看到遗漏了id=2的注解)

package com.anialy.test.annotation;

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


public class CustomizedAnnotationTracker {
	public static void trackAnnotation(
			List<Integer> annotations, Class<?> clazz){
		for(Method m : clazz.getDeclaredMethods()){
			CustomizedAnnotation anno = 
					m.getAnnotation(CustomizedAnnotation.class);
			if(anno != null){
				System.out.printf("Annotation id: %d, description: %s\n"
						, anno.id(), anno.description());
				
				// 集合annotations中的元素(id)如果出现在TestBean中
				// 则将该id从 annotations集合中移除
				annotations.remove(new Integer(anno.id()));
			}
		}
		   
		for(int i : annotations){
			System.out.printf("Missing annotation id: %d\n", i);
		}
	}
	
	public static void main(String[] args) {
		List<Integer> annotations = new ArrayList<Integer>();
		Collections.addAll(annotations, 1, 2, 3);
		trackAnnotation(annotations, TestBean.class);
	}
}

输出:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值