反射类的使用ReflectUtil(设置set和获取get某个类属性值)

import java.lang.reflect.Field;  
import java.lang.reflect.Method;  
import java.lang.reflect.Modifier;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class ReflectUtil {
 private static final Log logger = LogFactory.getLog(ReflectUtil.class);  
  
    public static void setFieldValue(Object target, String fname, Class ftype,  
            Object fvalue) { //设置字段值  如:username 字段,setUsername(String username)
        if (target == null 
                || fname == null 
                || "".equals(fname)  
                || (fvalue != null && !ftype.isAssignableFrom(fvalue.getClass()))) {//如果类型不匹配,直接退出
            return;  
        }  
        Class clazz = target.getClass();  
        try {  //先通过setXxx()方法设置类属性值
         String methodname="set"  + Character.toUpperCase(fname.charAt(0)) + fname.substring(1);
         System.out.println(methodname);
            Method method = clazz.getDeclaredMethod(methodname, ftype); //获取定义的方法
            if (!Modifier.isPublic(method.getModifiers())) {   //设置非共有方法权限
                method.setAccessible(true);  
            }  
            method.invoke(target, fvalue);  //执行方法回调
        } catch (Exception me) {//如果set方法不存在,则直接设置类属性值
            if (logger.isDebugEnabled()) {  
                logger.debug(me);  
            }  
            try {  
                Field field = clazz.getDeclaredField(fname);   //获取定义的类属性
                if (!Modifier.isPublic(field.getModifiers())) {   //设置非共有类属性权限
                    field.setAccessible(true);  
                }  
                field.set(target, fvalue); //设置类属性值
               
            } catch (Exception fe) {  
                if (logger.isDebugEnabled()) {  
                    logger.debug(fe);  
                }  
            }  
        }  
    }  
    public static Object getFieldValue(Object target, String fname, Class ftype 
           ) {//获取字段值  如:username 字段,getUsername()
     if (target == null 
                || fname == null 
                || "".equals(fname)  
                ) {  
            return null;  
        }  
     Class clazz = target.getClass();  
        try {   //先通过getXxx()方法获取类属性值
         String methodname="get"  + Character.toUpperCase(fname.charAt(0)) + fname.substring(1);
         System.out.println(methodname);
            Method method = clazz.getDeclaredMethod(methodname); //获取定义的方法
            if (!Modifier.isPublic(method.getModifiers())) {   //设置非共有方法权限
                method.setAccessible(true);  
            }  
            return method.invoke(target); //方法回调,返回值 
        } catch (Exception me) {//如果get方法不存在,则直接获取类属性值
            if (logger.isDebugEnabled()) {  
                logger.debug(me);  
            }  
            try {  
                Field field = clazz.getDeclaredField(fname);   //获取定义的类属性
                if (!Modifier.isPublic(field.getModifiers())) {    //设置非共有类属性权限
                    field.setAccessible(true);  
                }  
                return field.get(target);//返回类属性值
            } catch (Exception fe) {  
                if (logger.isDebugEnabled()) {  
                    logger.debug(fe);  
                }  
            }  
        } 
        return null;
    }
   
    public static void main(String[] args) {
     TestMethod testm=new TestMethod();
     ReflectUtil.setFieldValue(testm, "mtd", String.class, "sdf");
     System.out.println(testm.getMtd());
     ReflectUtil.getFieldValue(testm, "mtd", String.class);
 }

 

 public class TestMethod {

 private String mtd;

 public String getMtd() {
  return mtd;
 }

// private void setMtd(String mtd) {
//  this.mtd = mtd;
// }
 
}

----------------------------------------------------------------------------------------------------------------------------------------

项目中:


package com.xxx.dhm.portalMS.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * 反射工具类
 *
 */
public class ReflectUtil
{
    
    private static final Log logger = LogFactory.getLog(ReflectUtil.class);
    
    @SuppressWarnings("unchecked")
    public static void setFieldValue(Object target, String fname, Class ftype,
            Object fvalue)
    {
        if (target == null
                || fname == null
                || "".equals(fname)
                || (fvalue != null && !ftype.isAssignableFrom(fvalue.getClass())))
        {
            return;
        }
        Class clazz = target.getClass();
        try
        {
            Field field = clazz.getDeclaredField(fname);
            if (!Modifier.isPublic(field.getModifiers()))
            {
                field.setAccessible(true);
            }
            field.set(target, fvalue);
            
        }
        catch (Exception me)
        {
            if (logger.isDebugEnabled())
            {
                logger.debug(me);
            }
        }
    }
    
    /**
     * 通过反射机制克隆一个对象
     * @param obj
     * @return
     * @throws Exception
     */
    public static Object copyObject(Object obj) throws Exception
    {
        Field[] fields = obj.getClass().getDeclaredFields();
        Object newObj = obj.getClass().newInstance();
        for (int i = 0, j = fields.length; i < j; i++)
        {
            String propertyName = fields[i].getName();
            Object propertyValue = getProperty(obj, propertyName);
            setProperty(newObj, propertyName, propertyValue);
        }
        return newObj;
        
    }
    
    // 反射调用setter方法,进行赋值
    @SuppressWarnings("unchecked")
    private static Object setProperty(Object bean, String propertyName,
            Object value) throws Exception
    {
        Class clazz = bean.getClass();
        try
        {
            Field field = clazz.getDeclaredField(propertyName);
            Method method = clazz.getDeclaredMethod(getSetterName(field.getName()),
                    new Class[] { field.getType() });
            return method.invoke(bean, new Object[] { value });
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    
    // 反射调用getter方法,得到field的值
    @SuppressWarnings("unchecked")
    public static Object getProperty(Object bean, String propertyName) throws Exception
    {
        Class clazz = bean.getClass();
        try
        {
            Field field = clazz.getDeclaredField(propertyName);
            Method method = clazz.getDeclaredMethod(getGetterName(field.getName()),
                    new Class[] {});
            return method.invoke(bean, new Object[] {});
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    
    // 根据field名,得到getter方法名
    private static String getGetterName(String propertyName)
    {
        String method = "get" + propertyName.substring(0, 1).toUpperCase()
                + propertyName.substring(1);
        return method;
    }
    
    // 根据field名,得到setter方法名
    private static String getSetterName(String propertyName)
    {
        String method = "set" + propertyName.substring(0, 1).toUpperCase()
                + propertyName.substring(1);
        return method;
    }
    
    /**
     * 普通的JavaBean对象转换成Map数据类型。
     * 将普通的JavaBean对象转换成Map数据类型,其中JavaBean声明的变量名作为Map类型的key,
     * 该变量的值,作为其Map数据类型相应key的值。
     *
     * @param obj
     *            - 普通JavaBean对象
     * @return 返回Map数据类类型
     *
     * @return Map<String,Object> 返回Map数据类型
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getObjectAsMap(Object obj)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        if (obj == null)
        {
            return map;
        } else if ( obj instanceof Map ) {
            return (Map) obj;
        }
        
        Class clazz = obj.getClass();
        Method[] methods = clazz.getMethods();
        String methodname = "";
        for (int i = 0; i < methods.length; i++)
        {
            methodname = methods[i].getName();
            if (methodname.startsWith("get"))
            {
                try
                {
                    Object value = methods[i].invoke(obj);
                    if( value != null && (value instanceof String ) ) {
                        String str = (String) value;
                        value = str.trim();
                    }
                    map.put(getFieldName(methodname), value);
                }
                catch (IllegalArgumentException e)
                {
                    logger.debug("Convert JavaBean to Map Error!", e);
                }
                catch (IllegalAccessException e)
                {
                    logger.debug("Convert JavaBean to Map Error!", e);
                }
                catch (InvocationTargetException e)
                {
                    logger.debug("Convert JavaBean to Map Error!", e);
                }
            }
        }
        return map;
    }
    
    private static String getFieldName(String str)
    {
        String firstChar = str.substring(3, 4);
        String out = firstChar.toLowerCase() + str.substring(4);
        return out;
    }
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值