随笔 - 0, 文章 - 75, 评论 - 0, 引用 - 0
数据加载中……

java注解(下)

为注解增加基本属性:



什么是注解的属性:一个注解就相当于一个胸卡,如果胸前贴了胸卡,就是该单位的员工,否则就不是。如果还想区分是该公司里哪个部门的员工,这时候可以为胸卡再增加一个属性来进行区分


加了属性的标记效果为:@MyAnnotation(department="development")



定义属性


---------------------------------------------------------


@Retention(RetentionPolicy.RUNTIME)
//指定注解生命周期
@Target({ElementType.METHOD,ElementType.TYPE})
//指定注解作用的范围
public @interface MyAnnotation {
String color() default
"bule";
String value(); //特殊方法,当只有一个属性时,不用写value =
int[]
arrayAttr() default {3,4,5};
//返回枚举类型的
EnumTest.TrafficLamp
lamp() default
EnumTest.TrafficLamp.RED;
//返回Annotation类型
MetaAnnotation
annotationAttr() default @MetaAnnotation("abc");
}


---------------------------------------------------------



应用属性


---------------------------------------------------------


@MyAnnotation(annotationAttr=@MetaAnnotation("bbb")
,color="red",value="abc",arrayAttr={1,2,3})
public class AnnotationTest {


public static void main(String[] args)
{
if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){
//哪个注解在不在
MyAnnotation annotation =
AnnotationTest.class.getAnnotation(MyAnnotation.class);
System.out.println(annotation.color());
System.out.println(annotation.value());
System.out.println(annotation.arrayAttr().length);
System.out.println(annotation.lamp().nextLamp().name());
//输出枚举元素的名
System.out.println(annotation.annotationAttr().value());
}
}



---------------------------------------------------------



定义属性可以为:


8个基本类型,String 、Class类型、枚举类型、注解类型、还可以是前面这些类型的数组

posted on 2012-04-22 15:58 hantai 阅读(64) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: