`
zhaolei415
  • 浏览: 166082 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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());
		}
	}

}


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




2
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics