美文网首页
JavaBean的属性用反射访问的基础知识

JavaBean的属性用反射访问的基础知识

作者: exmexm | 来源:发表于2017-10-21 17:22 被阅读0次
    1、简单利用配置文件以及反射生成一个实体类:

    配置 文件内容:

    image.png

    代码实现:

    package com.winney.dayst;
    
    import java.io.IOException;
    import java.util.Properties;
    import java.util.Set;
    
    public class Winney {
    
        public static void main(String[] args) {
            Properties pros = new Properties();
            try {
                pros.load(Winney.class.getResourceAsStream("classConfig.properties"));
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("加载配置文件失败!");
            }
            String className = pros.getProperty("className");
            try {
                Set<String> set = (Set) Class.forName(className).newInstance();
                set.add("winney");
                set.add("hello");
                System.out.println(set.toString());
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
    
        }
    
    }
    
    2、利用通过javaBean的属性描述new一个propertyDescriptor,然后利用propertyDescriptor.getReadMethod或者propertyDescriptor.getWriteMethod获得setter和getter方法。

    代码如下:

    public class TestSetAGet {
    
        public static void main(String[] args)
                throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
            Person person = new Person("01", "person Wang");
            // 输出person的name属性 name->Name,getName->
            String propertyName = "Name";
            PropertyDescriptor pd = new PropertyDescriptor(propertyName, person.getClass());
            Method getMethod = pd.getReadMethod();
            String retVal = (String) getMethod.invoke(person, null);
            System.out.println(retVal);
    
            // 设置person的name setName
            Method setMethod = pd.getWriteMethod();
            retVal = (String) setMethod.invoke(person, "person LI");
            System.out.println(getMethod.invoke(person, null));
        }
    
    }
    
    3、BeanUtils对上面的知识点进行了封装

    相关文章

      网友评论

          本文标题:JavaBean的属性用反射访问的基础知识

          本文链接:https://www.haomeiwen.com/subject/nqebuxtx.html