注解的使用实例

package com.franky.annotation;

/**
 * @描述 注解的应用实例
 * @作者 franky
 * @日期 2014-12-31 下午3:16:00
 */


//显式指定注解值,如果数组属性只有一个元素那么可以省略大括号
@MyAnnotation(color = "red",value = "hello",arrValue=1,metaAnnotation=@MetaAnnotation("world"))
public class AnnotationTest {

	/**
	 * 每一个注解都是一个对象,java.lang包下的三个基本注解:
	 * @Override 方法覆盖注解
	 * @SuppressWarnings 取消对方法的显示警告
	 * @deprecated 方法过时注解
	 * 
	 */
	
	
	//给value()方法直接赋值,而color()方法已经有默认值
	@MyAnnotation("hello")
	public static void main(String[] args) {
		
		//调用过时方法
		show();
		
		//调用取消警告的方法
		suppressWarnings();
		
		//检查是否带有注解类
		boolean isAnnotation = AnnotationTest.class.isAnnotationPresent(MyAnnotation.class);
		//如果带有注解,那么获取注解对象
		if(isAnnotation){
			MyAnnotation myAnnotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);
			System.out.println(myAnnotation);
			//可以打印注解的属性值
			System.out.println(myAnnotation.color());
			System.out.println(myAnnotation.arrValue().length);
			System.out.println(myAnnotation.enumAttr().nextNum().name());
			System.out.println(myAnnotation.metaAnnotation().value());
		}
		
	}
	
	//注明方法为过时方法
	@Deprecated
	public static void show(){
		System.out.println("hello,world");
	}
	
	//过时方法注解,编译器可以通过编译
	@SuppressWarnings("deprecation")
	public static void suppressWarnings(){
		System.runFinalizersOnExit(true);
	}

}

自定义注解类MyAnnotation:

package com.franky.annotation;

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

/**
 * 
 * @描述 自定义的注解类	
 * @作者 franky
 * @日期 2014-12-31 下午3:42:15
 */

/**
 * 自定义注解需要加入元注解(枚举值),那么编译器在编译时不会去掉注解
 * RetentionPolicy.SOURCE  保留在原文件
 * RetentionPolicy.CLASS   保留在class文件
 * RetentionPolicy.RUNTIME 保留到运行时
 * 
 * ElementType.METHOD 说明自定义的注解可应用在方法上
 * ElementType.TYPE   说明自定义的注解可应用的类型上
 * ElementType的各种枚举值说明了注解可以加在哪些类型上
 * 
 * 注解的属性类型包括8种基本属性类型,String,Class,枚举类型,
 * 或者上面这些类型的数组
 * 
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyAnnotation {
	//属性的默认值
	String color() default "blue";
	//如果只有一个value方法需要赋值,那么可以直接进行赋值
	String value();
	//数组属性
	int[] arrValue() default {1,2,3};
	//枚举属性
	EnumAttr enumAttr() default EnumAttr.ONE;
	//注解属性
	MetaAnnotation metaAnnotation() default @MetaAnnotation("metaAnnotation");
}

自定义的注解MetaAnnotation:

package com.franky.annotation;

/**
 * @描述 自定义的注解
 * @作者 franky
 * @日期 2014-12-31 下午5:08:02
 */
public @interface MetaAnnotation {
	String value() default "ok";
}


使用的枚举类EnumAttr:

package com.franky.annotation;

/**
 * @描述 使用的枚举类
 * @作者 franky
 * @日期 2014-12-31 下午5:09:15
 */
public enum EnumAttr {
	ONE {
		@Override
		public EnumAttr nextNum() {
			return TWO;
		}
	},
	TWO {
		@Override
		public EnumAttr nextNum() {
			return THREE;
		}
	},
	THREE {
		@Override
		public EnumAttr nextNum() {
			return ONE;
		}
	};
	public abstract EnumAttr nextNum();
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章