ITeye博客

annotation的用法

elfkingw · 2013-05-13 23:31 · 技术 · 编程语言 · Markdown

1.创建一个自定义annotation

  

package plugintest;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定义annotation
 * @author elfkingw
 * 2013-5-13下午11:09:02
 *
 */
@Retention(RetentionPolicy.RUNTIME)   
@Target(ElementType.FIELD)
public @interface DataFiled {

	/**
	 * 中文名称
	 * @return
	 */
	public String cName();
	/**
	 * 数据类型
	 * @return
	 */
	public String dataType();
	/**
	 * 是否容许为空
	 * @return
	 */
	public boolean isNull();
	
}

 

2.自定义annotation使用

package plugintest;

/**
 * 
 * @author elfkingw 
 * 2013-5-13下午11:09:47
 * 
 */
public class UserVo {

	private String Id;
	@DataFiled(cName = "用户名", dataType = "String", isNull = false)
	private String userName;
	@DataFiled(cName = "密码", dataType = "String", isNull = false)
	private String password;

	public String getId() {
		return Id;
	}

	public void setId(String id) {
		Id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

 3.annotation 测试

package plugintest;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class AnnotationTest {

	public static void main(String[] args) {
		UserVo vo = new UserVo();
		vo.setId("1");
		vo.setPassword("123456");
		vo.setUserName("elfkingw");
		Class clazz = vo.getClass();
		Field filed[] = clazz.getDeclaredFields();
		try {
			for (int i = 0; i < filed.length; i++) {
				Field f = filed[i];
				String fieldname = f.getName();
				// 得到单个字段上的Annotation
				DataFiled dateFiled = f.getAnnotation(DataFiled.class);
				// 如果标识了Annotationd的话
				if (dateFiled != null) {
					System.out.print(dateFiled.cName()+":");
					StringBuffer getMethodName = new StringBuffer("get");
					getMethodName.append(fieldname.substring(0, 1)
							.toUpperCase());
					getMethodName.append(fieldname.substring(1));
					Method getMethod = clazz.getMethod(getMethodName.toString());
					System.out.println(getMethod.invoke(vo, null));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

评论(0)

暂无评论。

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