First Annotation Demo

前段时间用Hibernate时用注解(即annotation)的方式来定义元数据的映射,一直都很想知道annotation是怎么实现的,今天终于做了一个自己的annotation demo

1、定义一个annotation的接口

package annotation.test;

/**
 * @author longtop
 * 
 */
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Description {
	String column();

	String comment();
}

 

2、在类中引用annotation

package annotation.test;

public class TableTest {
	public String id;
	public String name;

	@Description(column = "id",comment="主键")
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Description(column = "name", comment = "用户名")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

 

3、一个测试类,取出annotation定义的元数据

package annotation.test;

import java.lang.reflect.Method;

public class Test {
	public static void main(String[] args) {
		String className = "annotation.test.TableTest";
		try {
			Class tableTest = Class.forName(className);

			Method[] method = tableTest.getMethods();
			Description des = null;
			for (int i = 0; i < method.length; i++) {
				Method meth = method[i];
				if (meth.isAnnotationPresent(Description.class)) {
					des = meth.getAnnotation(Description.class);
					//System.out.println(des.annotationType());
					System.out.println(des.column() + "  :  " + des.comment());
				}
			}

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

还有什么高级的应用,请大家不吝赐教阿。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值