反射获得属性方法上面的注解

来源:互联网 发布:淘宝海报源代码 编辑:程序博客网 时间:2024/05/22 03:35
 public static Map<String, Object> transBean2Map(Object obj) {  
  
        if(obj == null){  
            return null;  
        }          
        Map<String, Object> map = new HashMap<String, Object>();  
        try {  
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());  
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();  
                // 过滤class属性  
                if (!key.equals("class")) {  
                    // 得到property对应的getter方法  
                    Method method = property.getReadMethod();  
                    MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);   //判断是否有注解
                    if(annotation!=null){
                    //创建属性需要的对象
                    key = annotation.name();
                    /*Method writeMethod = property.getWriteMethod();
                    writeMethod.invoke(, name);*/
                      //  annotation2Bean(annotation,bean);
                      //  method.invoke(obj, bean);
                    }
                    Object value = method.invoke(obj);  
                    map.put(key, value);  
                }  
            }  
        } catch (Exception e) {  
            System.out.println("transBean2Map Error " + e);  
        }  
  
        return map;  
  
    }  

    



@Retention(RetentionPolicy.RUNTIME)
public @interface  MyAnnotation {
String name();


}




0 0
原创粉丝点击