反射调用get和set方法

package com.bwie.interview.dao;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class GetAndset {
    
    //通过PropertyDescriptor反映射调用set和get方法 ,PropertyDescriptor类表示JavaBean类通过存储器导出一个属性,
    
    //clazz类 ,propertyName所有字段名
    @SuppressWarnings("all")
    public static PropertyDescriptor getPropertyDescriptor(Class clazz,String propertyName){
        //StringBuffer不存在继承关系,无法进行强转,StringBuffer类中的方法主要偏重于对于字符串的变化,和String类的主要区别它仅一次开辟了内存空间
        StringBuffer sb = new StringBuffer();//构建一个可变字符串用来构建方法名称
        Method setMethod=null;
        Method getMethod=null;
        PropertyDescriptor propertyDescriptor=null;
        
        try {
            Field f = clazz.getDeclaredField(propertyName);
            if(f!=null) {
                //获取把方法名首字母改成大写
                String methodSuffix = propertyName.substring(0,1).toUpperCase()+propertyName.substring(1);
                //构建的set方法
                sb.append("set"+methodSuffix);
                setMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{f.getType()});
                sb.delete(0, sb.length());//清空整个可变字符串
                
                sb.append("get"+methodSuffix);
                getMethod = clazz.getDeclaredMethod(sb.toString(), new Class[] {});
                //构建一个属性描述器 把对应属性 propertyName 的 get 和 set 方法保存到属性描述器中
                propertyDescriptor = new PropertyDescriptor(propertyName, getMethod, setMethod);
            }
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return propertyDescriptor;
        
    }
    //设置属性值
    @SuppressWarnings("all")
    public static void setProperty(Object obj,String propertyName,Object value) {
        Class clazz = obj.getClass();//获取对象类型
        PropertyDescriptor pd = getPropertyDescriptor(clazz, propertyName);//获取 clazz 类型中的 propertyName 的属性描述器  
        Method setMethod = pd.getWriteMethod();//从属性描述器中获取set方法
        try {
            setMethod.invoke(obj, new Object[] {value});
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //获取属性值
    @SuppressWarnings("all")
    public static Object getProperty(Object obj,String propertyName) {
        Class clazz = obj.getClass();
        PropertyDescriptor propertyDescriptor = getPropertyDescriptor(clazz, propertyName);
        Object value=null;
        Method getMethod = propertyDescriptor.getReadMethod();
        try {
            value = getMethod.invoke(obj, new Object[] {});
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return value;
        
    }
    
    
    
    public static void main(String[] args) throws Exception {
        
        Class<?> clazz =Class.forName("com.bwie.interview.bean.User");
        Object obj = clazz.newInstance();
        //obj里面存储的是user
        Field[] field = clazz.getDeclaredFields();
        
        for (Field fields : field) {
            System.out.println(fields.getName());
            PropertyDescriptor pd = new PropertyDescriptor(fields.getName(), clazz);
            Method method = pd.getWriteMethod();//获取写的方法
            System.out.println(method.getName());
            fields.setAccessible(true);
            
            Map<String, Object> map = new HashMap<>();
            map.put("username", "abc");
            map.put("pwd", "123");
            
            Iterator<Entry<String, Object>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, Object> entry = it.next();
                // 调用这个方法
                if (entry.getKey().equals(fields.getName())) {
                    method.invoke(obj, entry.getValue());
                }
            }
        
        }
        for (Field fields : field) {
            PropertyDescriptor pd = new PropertyDescriptor(fields.getName(), clazz);
            Method method = pd.getReadMethod();//获取读的方法
            System.out.println(method);
            fields.setAccessible(true);
            Object invoke = method.invoke(obj);
            System.out.println(invoke);
        }
        
    }

   



//以下还没研究s

    /*
     *
     * //自动装载表单及验证
public class LoadForm {
    //表单装载
    public static Object parseRequest(HttpServletRequest request,HttpServletResponse response,Object bean) throws ServletException, IOException{
           //取得所有参数列表
           Enumeration<?> enums = request.getParameterNames();
           //遍历所有参数列表
           while(enums.hasMoreElements()){
            Object obj = enums.nextElement();
            try {
             //取得这个参数在Bean中的数据类开
             Class<?> cls = PropertyUtils.getPropertyType(bean, obj.toString());
             //把相应的数据转换成对应的数据类型
             Object beanValue = ConvertUtils.convert(request.getParameter(obj.toString()), cls);
             //填充Bean值
             PropertyUtils.setProperty(bean, obj.toString(), beanValue);
            } catch (Exception e) {
                //不显示异常 e.printStackTrace();
            }
           }
           return bean;
        }   
    }
     *
     *
     */

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值