自定义注解,核心逻辑代码--原创

今天翻看Java核心技术卷2看到注解这章,发现一直以来只注重了注解的应用,并没有实际的自己研究过注解,于是找度娘查了一下这方面的资料,代码附于下面

加了比较详细的注释,便于理解

AnnotationInterface接口为注解的实体接口,接口里面定义的方法为注解使用时接收的字段

举例说明   摘自Java核心技术卷2——743

@AnnotationInterface(name="tom",age=22)

元素的顺序无关紧要       

@AnnotationInterface(age=22,name="tom")

与上面的注解一样

@AnnotationInterface(age=22)

如果某个元素的值并未制定,那么就使用声明的默认值。上面的注解name的值为"null"

AnnotationInterface.java

package Annotation;

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

/**
 * 自定义注解接口
 * Target注解标识为FIELD,表示只能标识在字段声明上
 * 
 * Retention注解标识为RUNTIME,表示 编译器将把注释记录在类文件中,在运行时 VM 将保留注释,因此可以反射性地读取。
 * 
 * Documented注解为
 * 
 * 指示某一类型的注释将通过 javadoc 和类似的默认工具进行文档化。
 * 
 * 应使用此类型来注释这些类型的声明:其注释会影响由其客户端注释的元素的使用。
 * 
 * 如果类型声明是用 Documented 来注释的,则其注释将成为注释元素的公共 API 的一部分。
 * @author xiaoliwen
 * @date 2015-7-7
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnnotationInterface {
	String name() default "null";
	int age();
}

AnnotationMethod.java

package Annotation;
/**
 * 实际应用注解的地方
 * @author xiaoliwen
 * @date 2015-7-7
 */
public class AnnotationMethod {
	@AnnotationInterface(name="张三",age=1)
	User user;
	class User{
		private String name;
		private int age;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}
	}
}

AnnotationUtil.java

package Annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
 * 获取注解信息工具类
 * @author xiaoliwen
 * @date 2015-7-7
 */
public class AnnotationUtil {
	public static void getAnnotationInfo(Class<?> clazz)
	{
		String nameA="姓名";
		int ageA=0;
		//检索该字节码文件中的字段
		Field [] fields=clazz.getDeclaredFields();
		for (Field field : fields) {
			//如果指定类型的注释存在于此元素上,则返回 true,否则返回 false。
			if (field.isAnnotationPresent(AnnotationInterface.class)) {
				//得到指定注解对象
				AnnotationInterface annotationInterface=field.getAnnotation(AnnotationInterface.class);
				nameA=annotationInterface.name();
				ageA=annotationInterface.age();
				System.out.println(nameA+ageA);
			}
		}
	}
	public static void main(String[] args) {
		AnnotationUtil.getAnnotationInfo(AnnotationMethod.class);
	}
}
工具类为解析注解中的注入信息用,Spring中通过注解来构建实体类既为这个原理,将需要注入的bean的信息使用反射构建出真实对象,然后层层分析,得到想要的对象

第一次发这么多,文笔不好请多见谅

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值