ITeye博客

spring工具类AnnotationUtils和ClassUtils使用小结

jakoes · 2010-07-14 17:36 · Spring · 编程语言 · Markdown

假设有以下类:

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的值如图:

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)

暂无评论。

评论功能维护中,当前仅展示历史评论。