`

java学习之annotation注解学习一

 
阅读更多
注解相当于一门标记语言,在程序中加入注解等于为程序打上某种标记,没加标示没有这种标记,以后javac编辑器,开发工具和其他程序可以利用反射来了解你的类和各种元素上有无任何标记,看你有什么标记就去做相应的事,标记可以加在包,类,方法,字段,方法的参数以及局部变量上

参考
http://www.cnblogs.com/linjiqin/archive/2011/02/16/1956426.html
学习时候写的demo

java中有四种元注解,专门注解其他的注解,分别如下:
1.@Retention元注解 表示需要在什么级别保留该注解信息,也就是生命周期.可选的
  RetentionPoicy参数有:
  //RetentionPolicy.SOURCE: 停留在java源文件,被编译器丢掉
  //RetentionPolicy.CLASS:停留在class文件中,但会被VM丢弃(默认)
  /RetentionPolicy.RUNTIME:内存中的字节码,VM将在运行时也保留注解,因此可以通过反射机制读取注解的信息


2.@Target元注解,默认值为任何元素,表示该注解用于什么地方。
  可用的ElementType参数包括:
  //ElementType.CONSTRUCTOR: 构造器声明
  //ElementType.FIELD: 成员变量、对象、属性(包括enum实例)
  //ElementType.LOCAL_VARIABLE: 局部变量声明
  //ElementType.METHOD方法声明
  //ElementType.PACKAGE包声明
  //ElementType.PARAMETER参数声明
  //ElementType.TYPE类,接口或者enum声明

3.@Documented将注解包含在JavaDoc中

4.@Inheried允许子类继承父类中的注解

下面是我写的一个简单例子:
package test.annotations;

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

import test.enums.Gender;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyAnnotation {
	//为注解添加属性
	String color();
	//为属性添加默认值
	String value() default "我是注解";
	//
	int[] array() default {1,2,3,4};
	
	//添加一个枚举类型
	Gender gender() default Gender.MAN;
	
	//添加一个注解类型
	MetaAnnotation metaAnnotation() default @MetaAnnotation(brithday="2014年5-5");
}


//简单的注解
package test.annotations;

public @interface MetaAnnotation {
	String brithday();
}

//简单的枚举
package test.enums;

public enum Gender {
	MAN{
		public String getName(){
			return "男";
		}
	},
	WOMEN{
		public String getName(){
			return "女";
		}	
	};
	public abstract String getName();
}


最后写一个测试类来测试:
package test.app;

import test.annotations.MetaAnnotation;
import test.annotations.MyAnnotation;
import test.enums.Gender;

//调用注解并赋值
@MyAnnotation(color="red",array={1,2,3},gender=Gender.MAN,metaAnnotation=@MetaAnnotation(brithday="2014年5-5"))
public class AnnotationApp {
	public static void main(String[] args){
		//检查AnnotationApp类是否有MyAnnotation注解
		if(AnnotationApp.class.isAnnotationPresent(MyAnnotation.class)){
			//若存在就获取注解
			MyAnnotation myAnnotation = AnnotationApp.class.getAnnotation(MyAnnotation.class);
			System.out.println(myAnnotation);
			//获得注解的属性
			int[] arrs = myAnnotation.array();
			for(int arr:arrs){
				System.out.println(arr);
			}
			System.out.println(myAnnotation.color());
			System.out.println(myAnnotation.gender());
			//获取注解的注解属性
			MetaAnnotation metaAnno = myAnnotation.metaAnnotation();
			System.out.println(metaAnno.brithday());
			
			System.out.println(myAnnotation.value());
		}
	}
}


结果如下:

  • 大小: 11.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics