如何使用反射设置参数的值&&关于反射的初级

如何获得class?

--有三种方法:类名.Class,对象.getClass(),Class.forName("完整类名(eg:java.lang.String)")。

reflect中的类有Field,Method,Constructor,使用时很相似;

如何使用反射设置一个类中各属性的值?

BeanUtils类:

package com.arj.reflection;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;


public class BeanUtils {

    /**
     * 给对象中的属性赋值,使用java.reflect.Method
     * @param obj
     * @param map
     * @return object
     */
    @SuppressWarnings("rawtypes")
    public static void populate(Object obj, Map map) {
        if(obj == null){
            throw new RuntimeException("对象为空");
        }
        
        if(map == null){
            throw new RuntimeException("没有值");
        }
        
        Method[] methods = obj.getClass().getDeclaredMethods();
        try {
            // map的遍历使用迭代器
            for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
                Map.Entry  entry = (Map.Entry) iterator.next();
                String propertyName = (String) entry.getKey();
                Object propertyValue = entry.getValue();
                
                for (Method method : methods) {
                    // 拼方法名
                    String methodName = "set"+ propertyName.substring(0, 1).toUpperCase()+propertyName.substring(1);
                    // 验证法发明是否相等
                    if(methodName.equals(method.getName())){
                        method.invoke(obj,propertyValue);
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    @SuppressWarnings("rawtypes")
    /**
     * TODO 给对象设置参数使用java.beans.*包
     * @param obj
     * @param map
     * @return
     */
    public static void populateByBeans(Object obj, Map map) {
        BeanInfo beanInfo = null;
        PropertyDescriptor[] propertyDescriptors = null;
        Method method = null;
        
        try {
            if(obj == null){
                throw new RuntimeException("对象为空");
            }
            
            beanInfo = Introspector.getBeanInfo(obj.getClass());
            // TODO 得到该类的所有属性的描述,运行后会自动添加一个name="class"的属性描述
            propertyDescriptors = beanInfo.getPropertyDescriptors();
            
            // TODO 遍历该属性描述数组,由属性找到方法设置属性值
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                // 一定要过滤name="class"的属性,否则会报错
                if(propertyDescriptor.equals("class")){
                    continue;
                }
                
                method = propertyDescriptor.getWriteMethod();
                
                if(method != null){
                    for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
                        Map.Entry entry = (Map.Entry) iterator.next();
                        String propertyName = (String) entry.getKey();
                        Object propertyValue = entry.getValue();
                        
                        // 验证属性名是否相等
                        if(propertyName.equals(propertyDescriptor.getName())){
                            method.invoke(obj, propertyValue);
                        }
                    }
                }
                
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
    }
}
BeanUtils

测试类:

其中有两种方式生成类的对象:

--User user = (User)User.class.newInstance();

--User user= new User();

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class MethodTest1 {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        User user = new User();
        Map  map = new HashMap();
        map.put("userId", 1);
        map.put("userName", "zhangsan");
        map.put("password", "11");
        map.put("salary", 11f);
        map.put("birthday", new Date());
        
        BeanUtils.populate(user,map);
        System.out.println(user);
    }

}
MethodTest
import java.util.HashMap;
import java.util.Map;

public class BeansTest1 {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args) {
        User user = null;
        Map  map = new HashMap();
        map.put("userId", 1);
        map.put("userName", "zhangsan");
        map.put("password", "11");
        map.put("salary", 11f);
        map.put("birthday", new Date());
        
        try {
            user = (User)User.class.newInstance();
            BeanUtils.populateByBeans(user,map);
            System.out.println(user);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
BeansTest

 

posted @ 2013-07-17 13:25  PS_popcorn  阅读(552)  评论(0编辑  收藏  举报