---
title: "spring工具类AnnotationUtils和ClassUtils使用小结"
author: "jakoes"
date: "2010-07-14T17:36:08Z"
tags: []
categories: ["编程语言"]
slug: "spring-annotationutils-classutils"
draft: false
lastmod: "2010-07-14T17:44:25Z"
id: 712753
url: "https://jakoes.iteye.com/blog/712753"
---

假设有以下类：

```java
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的定义:

```java
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Required {

}
```



```java
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {

	public String desc();
	
	public String[] allowedValues() default {};

	public String defaultValue() default "";
}

```


方法一：

```java
AnnotationUtils.getAnnotationAttributes(Annotation)
```

此方法可以将指定的annotation的所有属性都及值都获取到，并以key-value的形式存放到map里。
方法二：

```java
public static Object getValue(Annotation annotation, String attributeName)
```

此方法可以获取指定annotaion中某个属性的值。

示例：

```java
		//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的值如图：

![](http://dl.iteye.com/upload/attachment/277754/813f208d-1860-3961-80d3-3b616f5e2b64.gif)

obj的值为“卡类型”。

AnnotationUtils写得虽功能简单，但封装极其简练，堪称经典。另，此类是抽象类，我们可以在它上面进行扩展。

我们来看另一个类ClassUtils：
有时我们获取到的class或interface为如下的形式：

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

```java
cps.apm.util.fileprocessor.annotation.Required
```

或

```java
Required
```


spring的ClassUtils给我们提供的这样的方法：

```java
ClassUtils.getShortName() //获取短类名，如上例中的：Required
ClassUtils.getClassFileName() //获取类文件名，如上例中的：Required.class
ClassUtils.getPackageName() //获取包，如上例中的：cps.apm.util.fileprocessor.annotation
ClassUtils.getQualifiedName() //获取包名+类名，如上例中的：cps.apm.util.fileprocessor.annotation.Required

```