java自定义注解

我一直认为注解是一种高大深的技术,通过学习,慢慢认识到注解其实和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;
	   }

 

       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值