spring工具类AnnotationUtils和ClassUtils使用小结

假设有以下类:
public class TravelModel {


@Required
@Column(desc="卡类型",allowedValues={"0","1"},defaultValue="0")
private String cardType;

@Required
@Column(desc="卡号")
private String acctCard;

...
}

此bean的大概的含义为,使用两个自定义的annotation来标注field。如此field是否是必需的,field的中文描述,允许的值,默认值。

两个Annotation的定义:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Required {

}


@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {

public String desc();

public String[] allowedValues() default {};

public String defaultValue() default "";
}


方法一:
AnnotationUtils.getAnnotationAttributes(Annotation)

此方法可以将指定的annotation的所有属性都及值都获取到,并以key-value的形式存放到map里。
方法二:
public static Object getValue(Annotation annotation, String attributeName)

此方法可以获取指定annotaion中某个属性的值。

示例:
		//get all fiedls 
Field[] fields = TravelModel.class.getDeclaredFields();
for(Field f:fields){
Annotation[] annos = f.getAnnotations();
for(Annotation a:annos){
if(a instanceof Column){
//get all attributes
Map map = AnnotationUtils.getAnnotationAttributes(a);
//get value
Object obj = AnnotationUtils.getValue(a, "desc");
}
...


结果:
map的值如图:

[img]http://dl.iteye.com/upload/attachment/277754/813f208d-1860-3961-80d3-3b616f5e2b64.gif[/img]

obj的值为“卡类型”。

AnnotationUtils写得虽功能简单,但封装极其简练,堪称经典。另,此类是抽象类,我们可以在它上面进行扩展。

我们来看另一个类ClassUtils:
有时我们获取到的class或interface为如下的形式:
interface cps.apm.util.fileprocessor.annotation.Required

但其实我们想要的是下面的形式:
cps.apm.util.fileprocessor.annotation.Required


Required


spring的ClassUtils给我们提供的这样的方法:
ClassUtils.getShortName() //获取短类名,如上例中的:Required
ClassUtils.getClassFileName() //获取类文件名,如上例中的:Required.class
ClassUtils.getPackageName() //获取包,如上例中的:cps.apm.util.fileprocessor.annotation
ClassUtils.getQualifiedName() //获取包名+类名,如上例中的:cps.apm.util.fileprocessor.annotation.Required
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值