java内省

  内省:操作javabean的属性,属性指的是字段拥有get或set方法叫做属性

    /*   内省 Introspector    */
    public void test() throws Exception{
        BeanInfo info = Introspector.getBeanInfo(Person.class);
        PropertyDescriptor[] pds = info.getPropertyDescriptors();
        for(PropertyDescriptor pd : pds){
            System.out.println(pd.getName());
        }
    }
    @Test
    public void test1() throws Exception{
        Person p =  new Person();
        PropertyDescriptor pdS = new PropertyDescriptor("name", Person.class);
        Method methodS = pdS.getWriteMethod();
        methodS.invoke(p, "大梦");
        PropertyDescriptor pd = new PropertyDescriptor("name", Person.class);
        Method method = pd.getReadMethod();
        System.out.println(method.invoke(p, null));
        System.out.println(pdS.getPropertyType());
    }

  这个有一个第三方jar,叫做BeanUtils(apche),运行这个第三方jar需要一个日志文件commons-loggin.jar

  这个BeanUtils可以支持8种的基本数据类型的相互转化,除此之外的类型转换都需要我们自己写注册转化器

 1     public void test() throws Exception, Exception, Exception {
 2         Person p = new Person();
 3         ConvertUtils.register(new Converter() {
 4             @Override
 5             public Object convert(Class type, Object value) {
 6                 if(value == null){
 7                     return null;
 8                 }
 9                 if(!(value instanceof String)){
10                     throw new ConversionException("数据不是String类型");
11                 }
12                 String str = (String) value;
13                 if(str.trim() == null){
14                     return null;
15                 }
16                 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
17                 try {
18                     return df.parse(str);
19                 } catch (ParseException e) {
20                     throw new ConversionException(e);
21                 }
22             }
23         },Date.class);
24         String brithday = "1920-09-06";    
25         BeanUtils.setProperty(p, "name", "duweneli");
26         BeanUtils.setProperty(p, "pwd", "123456");
27         BeanUtils.setProperty(p, "age", "23");
28         BeanUtils.setProperty(p, "brithday", brithday);
29         System.out.println(BeanUtils.getProperty(p, "name"));
30         System.out.println(BeanUtils.getProperty(p, "pwd"));
31         System.out.println(BeanUtils.getProperty(p, "age"));
32         System.out.println(BeanUtils.getProperty(p, "brithday"));
33     }
34     
35     public void test1(){
36         Map<Integer,String> map = new LinkedHashMap<Integer, String>();
37         map.put(1, "aa"); 
38         map.put(2, "bb"); 
39         map.put(3, "cc");
40         for(Map.Entry<Integer, String> entry : map.entrySet()){
41             Integer key = entry.getKey();
42             String value = entry.getValue();
43             System.out.println(key+"="+value);
44             
45         }

  

posted @ 2014-01-08 14:25  哎呦喂,我的小祖宗╰つ  阅读(247)  评论(0编辑  收藏  举报