码迷,mamicode.com
首页 > 编程语言 > 详细

回顾java Annotation(注解)

时间:2014-07-06 10:57:21      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:java   annotation   注解   

最近在学习中发现相当多的框架是通过注解来实现的。为了加深记忆,把注解重新做一下回顾。


首先注解不是注释。——但因为java语言内置了三个注解:@Override、@Deprecated、@SuppressWarnnings。第一个是通知编译器做方法覆盖检查;第二个是提醒程序员使用了过时的方法;第三个是通知编译器忽略警告。这三个内置注解用起来给人的感觉就象注释一样。而实际上注解的用法远不止这么简单,通过使用自定义注解有助于加深我们的理解。


使用自定义注解目的是为了给程序加上某些标记(这种标记也可称之为元数据),这些标记是给有关注需要的其他程序使用的。不关注的就直接忽略过去了。所以使用注解的完整过程包括三步:定义注解、使用注解、解析注解。和我们定义类、创建对象、使用对象是一样的。下面结合一个小例子分别说明:

第一步,定义注解

Annotation(注解)其实是一个接口,但不是用interface关键字而是用@interface,以示区别。因为的确和普通接口有区别——Annotation类型的方法必须是无参数、无异常抛出的;默认继承自java.lang.annotation.Annotation


先定义一个用于类的注解

package com.annotation.zjc;
import java.lang.annotation.*;

//以下三行是“元注解”,用于指明此注解的生命周期、使用范围和可被文档化
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface Description {
	String value();
}

再定义一个用于构造函数和方法的注解

package com.annotation.zjc;
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR,ElementType.METHOD})
@Documented
public @interface Resource {
	int id();
	String name();
	String type() default "Object";  //可以给出默认值
}

第二步,使用注解

注解可以使用在包,类,字段,方法,方法的参数以及局部变量上(最多见就是用在类和方法上,其他位置比较罕见)。使用了注解也就相当于创建了一个注解类的实例。

package com.annotation.zjc;

@Description("Inject use annotation")
//等同于@Description(value="Inject use annotation"),字段名称为value,可以用以上简写模式
public class ApplyAnnotation {
	
	@Resource(id=1,name="zhang",type="person")
	public ApplyAnnotation(){
		//init...
	}
	public void execute(Resource r){
		System.out.println(r.id()+"  "+r.name()+"  "+r.type());
	}
}

第三步,解析注解

package com.annotation.zjc;

import java.lang.reflect.Constructor;
public class testMain {
	public static void main(String[] args){
		ApplyAnnotation aa=new ApplyAnnotation();
		Class<?> objclass=null;
		try{
			objclass = Class.forName("com.annotation.zjc.ApplyAnnotation");
		}catch(Exception e){}
		
		if(objclass!=null&&objclass.isAnnotationPresent(Description.class)){
			Description des=objclass.getAnnotation(Description.class);//获取“注解对象”
			System.out.println(des.value());
		}
		
		Resource r=null;
		if(objclass!=null){
			Constructor<?> cons[]=objclass.getConstructors();//反射取得类的构造函数
			for(Constructor<?> con:cons){
				if(con.isAnnotationPresent(Resource.class)){
					r=(Resource)con.getAnnotation(Resource.class);//获取“注解对象”
				}
			}
		}

		if(r!=null)
			aa.execute(r);
	}
}

在实际情况中,往往是第一步、第三步都由框架或工具程序做了,我们只需要在自己的程序中使用注解即可。当然使用前要import相应的包文件。

回顾java Annotation(注解),布布扣,bubuko.com

回顾java Annotation(注解)

标签:java   annotation   注解   

原文地址:http://blog.csdn.net/zjc/article/details/36948641

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!