annotation的用法

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();
		}
	}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值