java注解

5,java注解
文档中三种基本的注解类型Override、SuppressWarnings、Deprecated,我们平时都用过了,接下来我们写自己注解类。
步骤一:
注解类:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface My1Annotation {

}

说明:在注解类中的注解Retention和Target称为元注解,其中Target中的值ElementType是一个数组类型其中的取值表明该注解可以在类的哪个地方用,Retention中RetentionPolicy是一个枚举类型的有三个取值:SOURCE 、CLASS 、RUNTIME 告送java编译器保留这个注解到什么时候。前面提到的Override、SuppressWarnings的Retention就是SOURCE 类型的Deprecated是RUNTIME 类型的。
步骤二:
使用注解类的类以及判断使用是否使用了注解类的类(大部分不是同一个类):
@My1Annotation()
public class AnnotationTest {

@My1Annotation()
public static void main(String[] args) throws Exception{
System.runFinalizersOnExit(true);
if(AnnotationTest.class.isAnnotationPresent(My1Annotation.class)){
My1Annotation annotation = (My1Annotation)AnnotationTest.class.getAnnotation(My1Annotation.class);
}

}

说明:使用步骤一中我们定义的注解类,并在main方法中判断我们这个类中是否使用了注解类。

========================华丽的分割线======================
步骤三:我们在注解类中添加属性
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface My2Annotation {
String color() default "blue";
String value();
int[] arrayAttr() default {3,4,4};
// EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED;
// MetaAnnotation annotationAttr() default @MetaAnnotation("lhm");
}

说明:可以作为注解类类型有String、数组、枚举、注解,类型value比较特殊在使用注解类该属性的时候直接使用字符串不用 value=“v1”当然你这样使用也是可以的。
步骤四:使用注解类的类以及判断是否使用了注解类的类
@ItcastAnnotation(color="red",value="ku6")
public class AnnotationTest {

public static void main(String[] args) throws Exception{

if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){
ItcastAnnotation annotation = (ItcastAnnotation)AnnotationTest.class.getAnnotation(ItcastAnnotation.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());
}
}

}


这部分内容是先前自己没有接触过的东西可能写的过程中有一些不严谨的地方,希望看到的童鞋们指正并一起讨论。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值