为注解增长各类属性

1、为注解增长基本属性

    一、定义基本类型的属性和应用属性 

        在注解类中增长String color(); 

        @MyAnnotation(color="red")

    二、用反射方式得到注解对应的实例对象后,再经过该对象调用属性对应的方法

MyAnnotation a = (MyAnnotation)AnnotationTest.class.getAnnotation(MyAnnotation.class); 

System.out.println(a.color()); 

能够认为上面这个@MyAnnotation是MyAnnotaion类的一个实例对象

    三、为属性指定缺省值

String color() default "yellow";

    四、value属性

String value() default "zxx"; 
若是注解中有一个名称为value的属性,且你只想设置value属性(即其余属性都采用默认值或者你只有一个value属性),那么能够省略value=部分,例如:@MyAnnotation("lhm")。

二 、为注解增长高级属性

    一、数组类型的属性

int [] arrayAttr() default {1,2,3};
@MyAnnotation(arrayAttr={2,3,4})
若是数组属性中只有一个元素,这时候属性值部分能够省略大括

    二、枚举类型的属性

EnumTest.TrafficLamp lamp() ;
@MyAnnotation(lamp=EnumTest.TrafficLamp.GREEN)

    三、注解类型的属性

MetaAnnotation annotationAttr() default @MetaAnnotation("xxxx");
@MyAnnotation(annotationAttr=@MetaAnnotation(“yyy”) )
能够认为上面这个@MyAnnotation是MyAnnotaion类的一个实例对象,一样的道理,能够认为上面这个@MetaAnnotation是MetaAnnotation类的一个实例对象,调用代码以下:
	MetaAnnotation ma =  myAnnotation.annotationAttr();
	System.out.println(ma.value());

3、代码说明

    一、LH.java

package staticimport.annotation;

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

import staticimport.enums.TrafficEnumTest;

@Retention(RetentionPolicy.RUNTIME)//元注解
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface LH {
	//字符串类型,带默认值
	String color() default "red";
	//字符串类型
	String value();
	//整型数组类型,带默认值
	int[] arrayAttr() default {1,2,3};
	
	//枚举类型,带默认值
	TrafficEnumTest.TrafficLampEnum lamp() default TrafficEnumTest.TrafficLampEnum.YELLOW;
	//注解类型,带默认值
	MetaAnnotation annotation() default @MetaAnnotation("xyz");
	
	//Class类型,带默认值
	Class<?> clazzAttr() default String.class;
}

    二、AnnotationTest.java

package staticimport.annotation;

//只有一个value属性值须要赋值,能够省略value=
//数组属性值只有一个,能够省略{}
@LH(color = "yellow", value = "abc", arrayAttr = 5, annotation = @MetaAnnotation("xxx"), clazzAttr = AnnotationTest.class)
@SuppressWarnings("deprecation")
public class AnnotationTest {

	public static void main(String[] args) {
		System.runFinalizersOnExit(true);
		AnnotationTest.sayHello();

		if (AnnotationTest.class.isAnnotationPresent(LH.class)) {
			LH lh = (LH) AnnotationTest.class.getAnnotation(LH.class);
			System.out.println(lh);
			System.out.println(lh.color());
			System.out.println(lh.value());
			System.out.println(lh.arrayAttr().length);
			System.out.println(lh.lamp().nextLamp());
			System.out.println(lh.annotation().value());
			System.out.println(lh.clazzAttr());
		}

	}

	// 标注本方法已过期,提示用户不要再使用!但不影响已经使用的!
	@Deprecated
	@LH("kkk")
	public static void sayHello() {
		System.out.println("Hello,LH!");
	}

}

    三、MetaAnnotation.java

package staticimport.annotation;

public @interface MetaAnnotation {
	String value();
}

    注:java

        注解属性类型能够是8大基本数据类型、String、Class及其调用类型、枚举、注解、基本数据类型数组数组

相关文章
相关标签/搜索