您的位置:首页 > 其它

自定义注解理解梳理

2015-10-10 15:58 375 查看

自定义注解

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

限制输入

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

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @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是测试类。

注解的使用场景远不是上面所罗列的,各位看官可以把自己的见解写在评论中,一同探讨学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  自定义注解