自定义注解理解梳理

来源:互联网 发布:linux 中文时间格式 编辑:程序博客网 时间:2024/06/16 01:54

自定义注解


自定义注解的使用很简单,通过@interface修饰就可以称之为注解,但是在使用的时候,却有很多门道。

限制输入

首先,自定义注解可以用来限制输入。例如:

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Annotationself {    enum fieldType {        STRING, INT    };    fieldType type();    String value();}

在这个例子中,我们限制了type的类型是枚举值,而value的类型是String类型。
在使用的时候,会强制我们使用限定的值。例如:

    @Annotationself(type = fieldType.STRING, value = "9")    void useAnnotation(){        System.out.println("say hello");    }

在该例中,就要求限制type只能输入枚举fieldType中的值,而value只能是String类型的值。

使用反射获取注解内容

其次,使用注解可以通过反射的方式获取到注解的内容,

Object c = Class.forName("com.wyb.annotation.user.UserTest")        .newInstance();Method[] methodArray = c.getClass().getDeclaredMethods();

上面代码可以获取到类所有方法。

methodArray[i].isAnnotationPresent((Class<? extends Annotation>)Annotationself.class)

这时isAnnotationPresent这个方法就有作用了,该方法可以判断获取到的方法是否是用Annotationself这个注解过的。同理,可以通过该方法来筛选出感兴趣的方法。之后就可以通过以下代码来获取需要的信息了。

Annotationself annotation =     methodArray[i].getAnnotation(Annotationself.class);String type = String.valueOf(annotation.type());

注:
上面代码中Annotationself 是自定义注解,
com.wyb.annotation.user.UserTest是测试类。

注解的使用场景远不是上面所罗列的,各位看官可以把自己的见解写在评论中,一同探讨学习。

0 0
原创粉丝点击