通过反射操作get、set方法

/**
 * 反射操作类,通过bean工具类更简单的操作get、set方法
 * 
 * @author chinoukin
 *
 */
public class RefelectTest {
 
    public static void main(String[] args)
            throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Student s = new Student();
        s.setName("张三");
        s.setAge(20);
 
        String propertyName = "name";
 
        Object retVal = getPropertyVal(propertyName, s);
        System.out.println(retVal);
 
        String newVal = "李四";
        setPropertyVal(propertyName, s, newVal);
        System.out.println(s.getName());
    }
 
    private static void setPropertyVal(String propertyName, Object s, Object newVal)
            throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        PropertyDescriptor pd = new PropertyDescriptor(propertyName, s.getClass());
        Method setMethod = pd.getWriteMethod();
        setMethod.invoke(s, newVal);
    }
 
    private static Object getPropertyVal(String propertyName, Object s)
            throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        PropertyDescriptor pd = new PropertyDescriptor(propertyName, s.getClass());
        Method getMethod = pd.getReadMethod();
        Object retVal = getMethod.invoke(s);
        return retVal;
    }
 
}
posted @ 2019-12-25 14:18  皮肤黝黑的小白  阅读(176)  评论(0)    收藏  举报