Java中常用注解

来源:互联网 发布:图象扭曲算法 编辑:程序博客网 时间:2024/06/07 19:10
JDK自带注解
@Override    @Deprecated      @Suppvisewarnings

常见第三方注解:
Spring:@Autried  @Service  @Component  @Repository
Mybatis: @InsertProvider  @UpdateProvider  @Options

注解的分类:
按运行机制分为:
源码注解:只在源码中有,编译成class文件时就没了。
编译时注解:在源码和class文件中都存在。如jdk自带注解。
运行时注解:在运行阶段起作用甚至会影响运行逻辑的注解。如autowired。

元注解:为注解的注解。

自定义注解:
上图中这些注解为元注解,其作用如下描述
@Target(ElementType.METHOD,ElementType.TYPE)
自定义注解作用域定义:其中METHOD为方法上声明,还有CONSTRUCTOR(构造方法声明)、FIELD(字段声明)、LOCAL_VARIABLE(局部变量声明)、PACKAGE(包声明)、PARAMETER(参数声明)、TYPE(类或接口声明)
@Retention(RetentionPolicy.RUNTIME)
自定义生命周期定义:RUNTIME(运行时存在,可通过反射读取)、CLASS(编译时会记录到class中,运行时忽略)、SOURCE(只在源码显示,编译时会丢弃)
@Inherited
自定义注解是否可被子类继承:有该注解表明允许子类继承,且对父类类的注解才有效。它只适用于类继承,接口的实现则无效。(个人灵感:可以通过注解继承实现接口公用参数的校验。)
@Documented
生成javadoc时会包含注解

解析注解:
概念:通过反射获取类、函数或成员上的运行时注解信息,从而实现动态控制程序运行时的逻辑。

代码如下:
import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface Decription {String desc();String author() default "";//如果不写默认值,在使用时必须赋值int value() default 18;}<pre name="code" class="java">import java.lang.reflect.Method;public class ParseAnnoction {public static void main(String[] args) throws Exception {Class clazz = Person.class;Decription de = (Decription)clazz.getAnnotation(Decription.class);//获得类注解信息System.out.println(de.desc() + de.author() + de.value());Method[] ms = clazz.getMethods();for(Method m : ms){Decription d = m.getAnnotation(Decription.class);if(null != d){//获得方法注解信息System.out.println(d.author() + d.desc() + d.value());}}}}
@Decription(author="cao", desc = "hello annocation" )public class Person {private String name;private int age;@Decription(desc = "this is getName method")public String getName(){return this.name;}public int getAge(){return age;}}
0 0
原创粉丝点击