手把手教你实现: 反射+元注解=自定义实现注解

1,290 阅读1分钟

1、定义注解(熟悉并掌握元注解的使用)

package com.yueqian.String_lianxi;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定义注解的实现
 * @author LinChi
 *
 */

/*定义注解*/
@Target(ElementType.FIELD)  //声明注解在何处可用
@Deprecated   //将注释包含在javadoc中
@Retention(RetentionPolicy.RUNTIME)   //表示注释将在运行时期被保留,可以通过反射机制读取注释中的信息
public @interface Person {
	/* 人的姓名 */
	public String name()default "";
	/* 人的年龄 */
	public int age();
	/* 人的性别 */
	public String sex() default "";
}

2、注解的使用

package com.yueqian.String_lianxi;
/**
 * 使用注解
 * @author LinChi
 *
 */
public class UsePerson {
	@Person(name="张三",age=18,sex="男")
	private String personInfo;

	public String getPersonInfo() {
		return personInfo;
	}

	public void setPersonInfo(String personInfo) {
		this.personInfo = personInfo;
	}
}

3、定义注解处理器

package com.yueqian.String_lianxi;
/**
 * 注解处理器
 */
import java.lang.reflect.Field;

public class PersonInfoUtil {
	public static void getPersonInfo(Class<?> clazz) {
		String personInfo = "学生信息:";
		Field[] files = clazz.getDeclaredFields();//通过反射获取注解
		for(Field file:files) {
			/*
			  isAnnotationPresent 如果指定类型的注释存在于此元素上,则返回 true,否则返回 false。
			  						此方法主要是为了便于访问标记注释而设计的。
			  getAnnotation  如果存在该元素的指定类型的注释,则返回这些注释,否则返回 null
			 */
			if(file.isAnnotationPresent(Person.class)) {
				Person person = (Person)file.getAnnotation(Person.class); 
				//注解信息的处理地方
				personInfo = "姓名:"+person.name()+"年龄:"+person.age()+"性别:"+person.sex();
				System.out.println(personInfo);
			}
		}
	}
}

注解处理器所用到的相关API

4、编写测试类

package com.yueqian.String_lianxi;

public class Test {
	public static void main(String[] args) {
		PersonInfoUtil.getPersonInfo(UsePerson.class);
	}
}

结果展示:

以后小伙伴们就可以用元注解+反射实现自定义注解啦!