Exception+

导航

 
    public class TravelModel {  
      
          
        @Required  
        @Column(desc="卡类型",allowedValues={"0","1"},defaultValue="0")  
        private String cardType;  
      
        @Required  
        @Column(desc="卡号")  
        private String acctCard;  
      
        ...  
    }  

此bean的大概的含义为,使用两个自定义的annotation来标注field。如此field是否是必需的,field的中文描述,允许的值,默认值。

 

两个Annotation的定义:

    @Documented  
    @Retention(RetentionPolicy.RUNTIME)  
    @Target(ElementType.FIELD)  
    public @interface Required {  
      
    }  

    @Documented  
    @Retention(RetentionPolicy.RUNTIME)  
    @Target(ElementType.FIELD)  
    public @interface Column {  
      
        public String desc();  
          
        public String[] allowedValues() default {};  
      
        public String defaultValue() default "";  
    }  

AnnotationUtils.getAnnotationAttributes(Annotation)  

  此方法可以将指定的annotation的所有属性都及值都获取到,并以key-value的形式存放到map里。
方法二:

  

    public static Object getValue(Annotation annotation, String attributeName)  


  此方法可以获取指定annotaion中某个属性的值。


Field[] fields = TravelModel.class.getDeclaredFields();  
for(Field f:fields){  
    Annotation[] annos = f.getAnnotations();  
    for(Annotation a:annos){  
        if(a instanceof Column){  
            //get all attributes  
            Map map = AnnotationUtils.getAnnotationAttributes(a);  
            //get value  
            Object obj = AnnotationUtils.getValue(a, "desc");  
        }  
        ...  

spring的ClassUtils给我们提供的这样的方法:

    ClassUtils.getShortName() //获取短类名,如上例中的:Required  
    ClassUtils.getClassFileName() //获取类文件名,如上例中的:Required.class  
    ClassUtils.getPackageName() //获取包,如上例中的:cps.apm.util.fileprocessor.annotation  
    ClassUtils.getQualifiedName() //获取包名+类名,如上例中的:cps.apm.util.fileprocessor.annotation.Required  

 

 

 

posted on 2017-09-20 15:39  Exception+  阅读(1069)  评论(0)    收藏  举报