我一直认为注解是一种高大深的技术,通过学习,慢慢认识到注解其实和xml配置文件非常类似,通过java反射取到注解中所配置的值;
元注解:
元注解的作用就是修饰其他注解。它们被用来提供对其它 annotation类型作说明。
【1】@Target,
【2】@Retention,
【3】@Documented,
【4】@Inherited
首先我定义一个@Tbale的注解用于和数据库做映射关系,我们知道数据库和实体映射在mybats中是在xml 中的。
@Target注解的作用是限制自定义注解所使用的范围,比如你定义的注解想用在类上,想用在方法上,以及属性上等,也可以用在多个上边,就在该注解定义,具体怎么定义的看下边:
@Target中有枚举类ElementType,我们打开java API 找到该枚举
比如我要让自定义的注解放在类上,
@Target(ElementType.TYPE)
如果我们想把自定义注解放在多个地方,
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention:注解保留的时间
枚举类RetentionPolicy
一般我们都会在运行时保留
@Retention(RetentionPolicy.RUNTIME)
@Documented用于描述其它类型的annotation应该被作为被标注的程序的公共API生成文档,具体可参考:http://blog.sina.com.cn/s/blog_b0d8ecae01019gi1.html
@Inherited 当有子类继承加有@Inherited自定义注解的类时自定义注解也会被子类继承。
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author pengbaowei
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Table {
public String name() default "";
public String dbName() default "ilp";
public enum DbType{ORACLE,MYSQL,DB2};
DbType fruitColor() default DbType.MYSQL;
}
这是一段利用反射从注解中取值的代码
/**
* 根据实体类的注解获和数据库表对应的字段,以及所对应的get方法名
* @param clazz
* @return
*/
private static Map<String,String> getHaveAnnotation(Class<?> clazz){
Map<String,String> map=new HashMap<String,String>();
//判断类上有没有@Table注解
if(clazz.isAnnotationPresent(Table.class)){
Table annotation = clazz.getAnnotation(Table.class);
if(!annotation.name().equals("")){
//将表名保存到map中
map.put("tableName", annotation.name());
List<Method> methodList = Arrays.asList(clazz.getDeclaredMethods());
for(Method method : methodList){
//判断是否有注解@Column并且不存在@Transient注解
if(method.isAnnotationPresent(Column.class)&&!method.isAnnotationPresent(Transient.class)){
//得到字段的名称
String name = method.getAnnotation(Column.class).name().toUpperCase();
if(!"".equals(name)){
//得到方法名
String methodName = method.getName();
map.put(name,name+";"+methodName);
}
}
}
}
}
return map;
}