`

JAVA自定义注解(一)

阅读更多
java中元注解有四个:

1.@Retention
2.@Target
3.@Document
4.@Inherited

1.@Retention
:注解保留的位置
  @Retention(RetentionPolicy.SOURCE) :
                                    注解保留在源代码中,class文件中不包含,
                                    功能是与编译器交互,用于代码检测。
                                    如@Override,@Suppress Warings。
                                     额外效率损耗发生在编译时
  @Retention(RetentionPolicy.CLASS)  :
                                    默认的保留策略,注解会在class字节码文件中在,
                                    但运行时无法获得,<br/>这个级别需要添加JVM加载
                                    时候的代理(javaagent),
                                    使用代理来动态修改字节码文件
   @Retention(RetentionPolicy.RUNTIME):
                                    注解会在class字节码文件中存在,在运行时可以通
                                    过反射获取到

2.@Target
: 注解的作用目标

@Target(ElementType.FIELD):作用于(定义)字段枚举常量(注解)
@Target(ElementType.TYPE) :作用于(定义)接口、类、枚举、注解(注解)
@Target(ElementType.METHOD) :作用于(定义)方法(注解)
@Target(ElementType.PARAMETER) :作用(定义)方法参数(注解)
@Target(ElementType.CONSTRUCTOR) :作用(定义)构造函数(注解)
@Target(ElementType.LOCAL_VARIABLE):作用(定义)局部变量(注解)
@Target(ElementType.ANNOTATION_TYPE):作用(定义)注解
@Target(ElementType.PACKAGE) :作用包  

3.@Document
: 该注解将被包含在javadoc中

4.@Inherited
:说明子类可以继承父类中的该注解

说明:
@interface 是自定义注解的写法,与接口不同
自定义注解可以显示传值,或隐式默认值
例如:
public @interface DoSomething {
    public String name() default "write";
}

显示:
@DoSomething(name = "walidake")//可以显式传值进来,此时
                name=walidake
public class UseAnnotation {

}

隐式:
@DoSomething//如果不传值,则默认name=我们定义的默认值,即我们上面
                定义的"write"
public class UseAnnotation {

}

当注解含有value()时不需要指定具体名称
public @interface DoSomething {
    public String value();
    public String name() default "write";
}

@DoSomething("walidake")
public class UseAnnotation {
//name的value值
}

“普通注解”只能用来注解“代码”,
而“元注解”只能用来注解 “普通注解”。

注解集成
public class UseInheritedAnnotation{
    @UnInheritable
    @Inheritable
    public static class Super{

    }

    public static class Sub extends  Super {

    }

    public static void main(String... args){

        Super instance=new Sub();
        System.out.println(Arrays.toString(instance.getClass().getAnnotations()));
    }
}

自定义注解语法格式:  
public @interface 注解名 {定义体}


经典案例:mybatis mapper接口的调用实现
以上一般在自定义Field Method Class 注解中使用


5.@Override 
:用于标识该方法继承自超类<br/>当父类的方法被删除或修改了,编译器会提示错误信息

6.@Deprecated
:表示该类或者该方法已经不推荐使用<br/>如果用户还是要使用,会生成编译的警告

7.@SuppressWarnings
:用于忽略的编译器警告信息

等等

后续章节(二) mybits 注解模拟
        (三) 使用场景分析与举例(Method 模板,节省代码量,简洁,减少重复代码)(Field参数默认值设置,减少重复代码)
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics