您的位置:首页 > 编程语言 > Java开发

Java注解笔记

2017-12-07 20:23 44 查看

前言

最近开始接触spring-boot,它能减少项目的配置文件数量,让项目结构变得极简并且提高开发效率。之所以能够极简,最大的原因就是spring-boot提供了一大堆(让我)”不知所谓”的注解,是最让我懵比的一点。而且我发现自己注解的基本知识几乎忘光了。所以有必要重新pick up一下基础知识。(尴尬-_-|||)

注解的作用

To be filled…

例子

@MyAnno.java

@Retention(RetentionPolicy.RUNTIME)//运行时起作用
@Target(ElementType.TYPE)//改注解作用于类或接口
public @interface MyAnno {

public String value() default "";

}


@AnnoMethod.java

@Retention(RetentionPolicy.RUNTIME)//works when runtime
@Target(ElementType.METHOD)//works on method...
public @interface AnnoMethod {

public String value() default "";

}


A.java

@MyAnno(value="new value is xxx")
public class A {

}


TestMyAnno.java

public class TestMyAnno {

public static void main(String[] args) {

Class<A> clazz = A.class;

Annotation[] annotations = clazz.getAnnotations();
System.out.println(annotations.length);
for (Annotation annotation : annotations) {
if(annotation instanceof MyAnno) {
System.out.println(annotation.getClass().getName());
MyAnno anno = (MyAnno)annotation;
System.out.println(anno.value());
}
}

Method[] methods = clazz.getMethods();
for (Method method : methods) {
if(method.isAnnotationPresent(AnnoMethod.class)) {
AnnoMethod am = method.getAnnotation(AnnoMethod.class);
System.out.println(am.value());
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java annotation