java 简单反射工具类

package com.sunjing.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.log4j.Logger;

/**
 * 反射工具
 * @author Administrator
 *
 */
@SuppressWarnings({"unchecked","deprecation"})
public class ReflectUtil {

    private static Logger m_logger = Logger.getLogger(ReflectUtil.class);
    
    
    /**
     *
     * 动态的绑定对象 通过类名
     * @param bean     执行对象
     * @param objName  做参数的对象的名称字符串
     */
    public static void setObjectFiledValue(Object bean, String objName,String objValue) {
        String methodName = getMethodName(objName);
        try {
            Method getMethod = bean.getClass().getMethod("get" + methodName, new Class[] {});
            Class cls = getMethod.getReturnType();
            // 把对象填充
            Method setMethod = bean.getClass().getMethod("set" + methodName, new Class[] { cls });
            setMethod.invoke(bean, new Object[] { objValue });
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }  
    
    
    /**
     * 创建对象通过类中的属性名
     * @param bean
     * @param objName
     * @return
     */  
    public static Object createObjectToObjName(Object bean, String objName) {
        String methodName = getMethodName(objName);
        try {
            Method getMethod = bean.getClass().getMethod("get" + methodName, new Class[] {});
            Class cls = getMethod.getReturnType();
            Object obj = getMethod.invoke(bean, new Object[] {});
            if (obj == null) {
                obj = cls.newInstance();
            }
            return obj;
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }  
    
    /**
     * 通过get***获取对象的基本类型字段值
     * @param obj  对象
     * @param fieldName 字段名
     * @return
     */
    public static Object getBaseFieldValue(Object obj,String fieldName){
        //得到方法名  
        String method = getMethodName(fieldName);
        try {
            //get方法  
            Method getMethod = obj.getClass().getMethod("get" + method, new Class[]{});  
            Object fieldValue = getMethod.invoke(obj, new Object[]{});
            return fieldValue;
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        }
        return null;
    }
    
    /**
     * 通过get***获取对象的对象字段值
     * @param obj  对象
     * @param objectFieldName 对象字段名
     * @return
     */
    public static Object getObjectFieldValue(Object obj,String objectFieldName){
        //得到方法名  
        String method = getMethodName(objectFieldName);  
        try {
            //get方法  
            Method getMethod = obj.getClass().getMethod("get" + method, new Class[]{});  
//            Class cls = getMethod.getReturnType();
            Object objFieldValue = getMethod.invoke(obj, new Object[]{});
            // 如果对象未初次化
//            if (objFieldValue == null) {
//                objFieldValue = cls.newInstance();
//            }
            return objFieldValue;
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        }
        return null;
    }
    
    
     /**
      * 动态赋值给系统对象 String Integer Long Float Date 等
      *
      * @param obj
      *            执行对象
      * @param fieldName
      *            属性
      * @param fieldValue
      *            参数
    */
    public static void bindFieldValue(Object obj,String fieldName,String fieldValue){
        
        //得到方法名  
        String method = getMethodName(fieldName);  
        try {
            //get方法  
            Method getMethod = obj.getClass().getMethod("get" + method, new Class[]{});  
            //得到参数类型
            Class cls = getMethod.getReturnType();  
            //set方法
            Method setMethod = obj.getClass().getMethod("set"+method,new Class[]{cls});
            
//            //当参数为空时直接赋予NULL值  
//            if (fieldValue.trim().equals("")) {
//                setMethod.invoke(obj, new Object[]{null});
//                return;
//            }  
            
            //根据不同的系统对象转换  
            if (cls == String.class) {
                setMethod.invoke(obj, new Object[] { fieldValue });
                return;
            } else if (cls == Integer.class || cls == Float.class || cls == Long.class || cls == Double.class
                    || cls == Byte.class || cls == Boolean.class || cls == Character.class || cls== java.sql.Timestamp.class) {
                Method valueOf = cls.getMethod("valueOf", new Class[] { String.class });
                Object valueObj = valueOf.invoke(cls, new Object[] { fieldValue });
                setMethod.invoke(obj, new Object[] { valueObj });
            } else if (cls == java.util.Date.class || cls == java.sql.Date.class) {
                Object dateObj = cls.newInstance();
                setMethod.invoke(obj, new Object[] { dateObj });
            }  
            
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            m_logger.error(e);
            e.printStackTrace();
        }
    }
    
    /**
     * 动态赋值给自定义对象
     * @param bean     执行对象
     * @param objName  做参数的对象
     * @param propertyName 做参数的对象的属性名称
     * @param value 参数
     */
    public static void bindSubObject(Object bean, String objName, String propertyName, String value) {

        String methodName = getMethodName(objName);
        try {
            Method getMethod = bean.getClass().getMethod("get" + methodName, new Class[] {});
            Class cls = getMethod.getReturnType();
            Object obj = getMethod.invoke(bean, new Object[] {});

//            // 判断参数为空,直接设置NULL值.
//            if (value.trim().equals("")) {
//                if (obj != null) {
//                    Method setMethod = bean.getClass().getMethod("set" + methodName, new Class[] { cls });
//                    setMethod.invoke(bean, new Object[] { null });
//                }
//                return;
//            }

            // 如果对象未初次化
            if (obj == null) {
                obj = cls.newInstance();
            }

            // 设置普通系统对象的属性
            bindFieldValue(obj, propertyName, value);
            // 把对象填充
            Method setMethod = bean.getClass().getMethod("set" + methodName, new Class[] { cls });
            setMethod.invoke(bean, new Object[] { obj });
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        }

    }  
    
    /**
     *
     * 动态的绑定对象 通过类名
     * @param bean     执行对象
     * @param objName  做参数的对象的名称字符串
     */
    public static void bindObject(Object bean, String objName) {

        String methodName = getMethodName(objName);
        try {
            Method getMethod = bean.getClass().getMethod("get" + methodName, new Class[] {});
            Class cls = getMethod.getReturnType();
            Object obj = getMethod.invoke(bean, new Object[] {});
            if (obj == null) {
                obj = cls.newInstance();
            }
            // 把对象填充
            Method setMethod = bean.getClass().getMethod("set" + methodName, new Class[] { cls });
            setMethod.invoke(bean, new Object[] { obj });
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }  
    
    /**
     *
     * 动态的绑定对象 通过对象
     * @param beanOne  对象1
     * @param beanTwo  对象2
     */
    public static void bindObjectFromObject(Object beanOne, Object beanTwo) {

        try {
            Method setMethod = beanOne.getClass().getMethod("set" + beanTwo.getClass().getSimpleName(), new Class[] { beanTwo.getClass() });
            setMethod.invoke(beanOne, new Object[] { beanTwo });
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }  
    
    /**
     * 获取对象方法的名字
     * @param objName  对象
     * @return
     */
    private static String getMethodName(String objName) {
        String funName = objName.substring(0, 1).toUpperCase();
        if (objName.length() > 1) {
            funName += objName.substring(1, objName.length());
        }
        return funName;
    }  
    
    
    /**
     *
     * @param className
     * @return
     */
    public static Object createObject(String className) {
        
        try {
            Class classType = Class.forName(className);
            Object classObj =  classType.newInstance();
            return classObj;
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        }
        return null;
    }
    
    
    /**
     *
     * @param className       类名(包含路径)
     * @param parameterTypes  构造函数的参数类型 Class[]
     * @param parameterValues 构造函数传入的值   Object[]
     * @return
     */
    public static Object createObjectToConstructor(String className,Class[] parameterTypes,Object[] parameterValues) {
        
        try {
            Class classType = Class.forName(className);
            Object classObj =  classType.getConstructor(parameterTypes).newInstance(parameterValues);
            return classObj;
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            m_logger.error(e);
        }
        return null;
    }
    
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tof21

支持原创

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值