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

2017-10-21  本文已影响0人  exmexm
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对上面的知识点进行了封装
上一篇 下一篇

猜你喜欢

热点阅读