保留字段维护类ObjectUtil

使用反射赋值。

Class clazz = object.getClass();
Method method = clazz.getDeclaredMethod("setLastUpdateDate", Date.class);
method.invoke(object, new Date());

 

如:

import java.lang.reflect.Method;
import java.util.Date;
import javax.servlet.http.HttpSession;


/**
 * 该类用来对系统中业务实体中的保留字段进行维护
 * 提供公用的方法签名
 *
 */
public class ObjectUtil {

	/**
	 * 设置创建人的一些属性值,不需要更新创建日期
	 * @param object
	 */
	@SuppressWarnings("unchecked")
	public static void setUpdatedBy(Object object) {
		@SuppressWarnings("rawtypes")
		Class clazz = object.getClass();
		HttpSession httpSession = GlobalSession.getHttpSession();
		try {
			SysUser dbCheckUser = (SysUser) httpSession.getAttribute(SessionKeys.SESSION_SYS_USER);
			Long userId = dbCheckUser.getId();

			Method setLastUpdateBy = clazz.getDeclaredMethod("setLastUpdateBy", Long.class);
			Method setLastUpdateDate = clazz.getDeclaredMethod("setLastUpdateDate", Date.class);

			setLastUpdateBy.invoke(object, userId);
			setLastUpdateDate.invoke(object, new Date());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 方法名称:setCreatedBy
	 * 功能描述:
	 * 设置创建人的一些属性值
	 * @param object
	 */
	@SuppressWarnings("unchecked")
	public static void setCreatedBy(Object object) {
		// 获得类对象
		@SuppressWarnings("rawtypes")
		Class clazz = object.getClass();
		HttpSession httpSession = GlobalSession.getHttpSession();
		try {
			SysUser dbCheckUser = (SysUser) httpSession.getAttribute(SessionKeys.SESSION_SYS_USER);
			Long userId = dbCheckUser.getId();
			Method setCreatedBy = clazz.getDeclaredMethod("setCreatedBy", Long.class);
			Method setLastUpdateBy = clazz.getDeclaredMethod("setLastUpdateBy", Long.class);
			Method setCreatedDate = clazz.getDeclaredMethod("setCreatedDate", Date.class);
			Method setLastUpdateDate = clazz.getDeclaredMethod("setLastUpdateDate", Date.class);
			Method setEnabledFlag = clazz.getDeclaredMethod("setEnabledFlag", String.class);

			setCreatedBy.invoke(object, userId);
			setLastUpdateBy.invoke(object, userId);
			setCreatedDate.invoke(object, new Date());
			setLastUpdateDate.invoke(object, new Date());
			setEnabledFlag.invoke(object, Constants.ENABLED_FLAG_Y);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}
}

 或:

/**
	 * 
	 * 设置target对象中名为fieldName的属性值为value
	 * 
	 * @param target
	 * @param fieldName
	 * @param value
	 * 
	 * @return target对象
	 * 
	 */
	public static Object setValueToField(Object target, String fieldName, Object value){
		Field[] fs = target.getClass().getDeclaredFields();
		for(Field f : fs){
			if(f.getName().equalsIgnoreCase(fieldName)){
				try {
					f.setAccessible(true);
					f.set(target, value);
				} catch (Exception e) {
					logger.error("\u8bbe\u7f6e\u503c\u51fa\u9519\uff0c\u8bf7\u68c0\u67e5 [target : " + target.getClass() + "][field : " + f.getName() + "][value : " + value.getClass() + "]");
					e.printStackTrace();
				}
				break;
			}
		}
		return target;
	}

 

 

。。

你可能感兴趣的:(object)