黑马程序员技术交流社区

标题: 【济南校区】Java中如何自定含义注解 [打印本页]

作者: 大山哥哥    时间: 2018-7-30 22:19
标题: 【济南校区】Java中如何自定含义注解
本帖最后由 大山哥哥 于 2018-7-30 22:23 编辑

自定义注解会需要元注解,此处先介绍元注解。

元注解

java中有四种元注解:@Retention、@Inherited、@Documented、@Target

@Retention

注解的保留位置(枚举RetentionPolicy),RetentionPolicy可选值:

@Inherited

声明子类可以继承此注解,如果一个类A使用此注解,则类A的子类也继承此注解

@Documented

声明注解能够被javadoc等识别(下面自定义注解处会有例子做介绍,点击查看

@Target

用来声明注解范围(枚举ElementType),ElementType可选值:

自定义注解介绍自定义注解使用场景

1和2这个没有做过类似实例,应该是像Hibernate中的使用注解映射Bean对象到数据库一样(此处为个人猜测,如有错误请留言指出),中间有检测和自动赋值。

自定义注解定义

定义一个自定义注解(不使用元注解):

[AppleScript] 纯文本查看 复制代码
public @interface MyAnnotation{}

定义一个自定义注解(使用元注解,每个元注解都是可选,非必选):

[AppleScript] 纯文本查看 复制代码
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Target({ElementType.FIELD,ElementType.METHOD})
public @interface MyAnnotation1{
    public String name() default "hello";
}

注解中可以声明成员方法,声明的成员方法为最终的注解里面的参数,成员方法可以使用default关键字设置默认值。上面的注解使用如:@MyAnnotation1(name=”ddd”);

自定义注解演示

新建一个自定义注解:

[AppleScript] 纯文本查看 复制代码
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Target({ElementType.FIELD,ElementType.METHOD})
@interface MyAnno{
    public String name() default "zhangsan";
    public String email() default "hello@example.com";
}

定义一个User类,来使用自定义注解:

[AppleScript] 纯文本查看 复制代码
class  User{

    @MyAnno(name = "zhang")
    private String name;

    @MyAnno(name = "zhang@example.com")
    private String email;


    @MyAnno(name = "sayHelloWorld")
    public String sayHello(){
        return "";
    }
}

[AppleScript] 纯文本查看 复制代码
Method[] methods = User.class.getMethods();
//Field[] fields = User.class.getFields();
Field[] fields = User.class.getDeclaredFields();
/*
    getFields:只能访问public属性及继承到的public属性
    getDeclaredFields:只能访问到本类的属性,不能访问继承到的属性

    getMethods:只能访问public方法及继承到的public方法
    getDeclaredMethods:只能访问到本类的方法,不能访问继承到的方法

    getConstructors:只能访问public构造函数及继承到的public构造函数
    getDeclaredConstructors:只能访问到本类的构造函数,不能访问继承到的构造函数
*/

for (Field field : fields) {
    MyAnno annotation = field.getAnnotation(MyAnno.class);
    if(annotation!=null){
        System.out.println("property="+annotation.name());
    }
}
for (Method method : methods) {
    MyAnno annotation = method.getAnnotation(MyAnno.class);
    if(annotation!=null){
        System.out.println("sayHello="+annotation.name());
    }
}

输出如下:

[AppleScript] 纯文本查看 复制代码
property=zhang 
property=zhang@example.com
sayHello=sayHelloWorld







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2