Jave 一些反射例子

1.

package common;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import model.BaseEntity;

public abstract class FillFields {

	private static String id = null;
	private static Integer deleteFlag = null;
	private static Date date = null;

	private static final Integer DELETE_FLAG_1 = new Integer(1);
	private static final Integer DELETE_FLAG_0 = new Integer(0);

	public static <T extends BaseEntity> T fillCreateFields(T t, String user) {

		id = UUID.randomUUID().toString();
		deleteFlag = DELETE_FLAG_0;
		date = new Date();

		fillId(t);
		fillDeleteFlag(t);
		fillCreateDate(t);
		fillCreator(t, user);
		fillUpdateDate(t);
		fillUpdater(t, user);
		fillOptimisticLock(t);

		return t;
	}

	public static <T extends BaseEntity> T fillUpdateFields(T t, String user) {

		date = new Date();

		fillUpdateDate(t);
		fillUpdater(t, user);
		fillOptimisticLock(t);

		return t;
	}

	public static <T extends BaseEntity> T fillDeleteFields(T t, String user) {

		deleteFlag = DELETE_FLAG_1;
		date = new Date();

		fillDeleteFlag(t);
		fillUpdateDate(t);
		fillUpdater(t, user);
		fillOptimisticLock(t);

		return t;
	}

	public static <T extends BaseEntity> T fillCancelDeleteFields(T t, String user) {

		deleteFlag = DELETE_FLAG_0;
		date = new Date();

		fillDeleteFlag(t);
		fillUpdateDate(t);
		fillUpdater(t, user);
		fillOptimisticLock(t);

		return t;
	}

	public static <T extends BaseEntity> T fillOptimisticLockFields(T t) {

		date = new Date();

		fillOptimisticLock(t);

		return t;
	}

	private static <T extends BaseEntity> T fillField(T t, String methodName, Class<?> fieldClass,
			Object value) {
		try {
			Class<?> clazz = t.getClass();
			Method method = clazz.getMethod(methodName, fieldClass);
			method.invoke(t, value);
			return t;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static <T extends BaseEntity> T fillId(T t) throws RuntimeException {
		t = fillField(t, "setId", String.class, id);
		return t;
	}

	private static <T extends BaseEntity> T fillDeleteFlag(T t) {
		t = fillField(t, "setDeleteFlag", Integer.class, deleteFlag);
		return t;
	}

	private static <T extends BaseEntity> T fillCreateDate(T t) {
		t = fillField(t, "setCreateTime", Date.class, date);
		return t;
	}

	private static <T extends BaseEntity> T fillCreator(T t, String user) {
		t = fillField(t, "setCreator", String.class, user);
		return t;
	}

	private static <T extends BaseEntity> T fillUpdateDate(T t) {
		t = fillField(t, "setUpdateTime", Date.class, date);
		return t;
	}

	private static <T extends BaseEntity> T fillUpdater(T t, String user) {
		t = fillField(t, "setUpdater", String.class, user);
		return t;
	}

	private static <T extends BaseEntity> T fillOptimisticLock(T t) {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		df.format(date);
		t = fillField(t, "setOptimisticLock", String.class, df.format(date));
		return t;
	}
}

 2.

package common;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.Column;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.ObjectMapper;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import entity.Condition;
import entity.Conditions;
import entity.Page;
import entity.Sort;

public class Building {

	public static Page page(HttpServletRequest request) {
		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		Page page = new Page(start, limit);
		return page;
	}

	public static List<Order> sortOne(HttpServletRequest request) {
		Map<String, String> orderMap = getOrder(request);
		List<Order> orderList = null;
		if (orderMap != null) {
			orderList = new ArrayList<Order>();
			if (orderMap.get("direction").equalsIgnoreCase("asc")) {
				orderList.add(Order.asc(orderMap.get("property")));
			} else if (orderMap.get("direction").equalsIgnoreCase("desc")) {
				orderList.add(Order.desc(orderMap.get("property")));
			} else {
				orderList = null;
			}
		}
		return orderList;
	}

	public static Map<String, String> getOrder(HttpServletRequest request) {
		Map<String, String> orderMap = null;
		try {
			String sortStr = request.getParameter("sort");
			if (sortStr != null) {

				ObjectMapper objectMapper = new ObjectMapper();
				Sort sort = objectMapper.readValue(sortStr.replaceAll("\\[", "").replaceAll("\\]", ""), Sort.class);
				String property = sort.getProperty() != null ? sort.getProperty().trim() : "";
				String direction = sort.getDirection() != null ? sort.getDirection().trim() : "";
				if (!property.equals("")) {
					orderMap = new HashMap<String, String>();
					if (direction.equals("") || direction.equalsIgnoreCase("asc")) {
						orderMap.put("property", property);
						orderMap.put("direction", "asc");
					} else if (direction.equalsIgnoreCase("desc")) {
						orderMap.put("property", property);
						orderMap.put("direction", "desc");
					} else {
						orderMap = null;
					}
				}
				return orderMap;
			} else {
				return null;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static <T> T entity(HttpServletRequest request, Class<T> clazz, String parameter) {
		try {
			String parameterStr = request.getParameter(parameter);
			if (parameterStr != null && !parameterStr.equals("") && !parameterStr.equals("{}")) {
				ObjectMapper objectMapper = new ObjectMapper();
				T t = objectMapper.readValue(parameterStr, clazz);
				return t;
			} else {
				return null;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static <T> List<T> entityList(String parameterStr, Class<T> clazz) {
		try {
			if (parameterStr != null && !parameterStr.equals("") && !parameterStr.equals("[]")) {
				List<T> list = null;
				ObjectMapper objectMapper = new ObjectMapper();
				list = new ArrayList<T>();
				JsonFactory f = new JsonFactory();
				JsonParser jp = f.createJsonParser(parameterStr);
				jp.nextToken();
				while (jp.nextToken() == JsonToken.START_OBJECT) {
					T t = objectMapper.readValue(jp, clazz);
					list.add(t);
				}
				return list;
			} else {
				return null;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static List<Criterion> criterionList(HttpServletRequest request, Object obj) {
		List<Criterion> criterionList = null;
		try {
			String parameterStr = request.getParameter("queryConditions");
			List<Conditions> list = entityList(parameterStr, Conditions.class);
			if (list != null) {
				criterionList = new ArrayList<Criterion>();
				Iterator<Conditions> it = list.iterator();
				while (it.hasNext()) {
					Conditions conds = it.next();
					Condition cond = new Condition(conds.getCondition());
					String propertyName = cond.getPropertyName();
					Object value = buildGetMethod(obj, cond.getValueProperty()).invoke(obj, new Object[0]);
					MatchMode matchMode = null;
					if (cond.getType().equalsIgnoreCase("like") || cond.getType().equalsIgnoreCase("ilike")) {
						if (cond.getLikeType() != null) {
							if (cond.getLikeType().equalsIgnoreCase("left")) {
								matchMode = MatchMode.START;
							} else if (cond.getLikeType().equalsIgnoreCase("right")) {
								matchMode = MatchMode.END;
							} else {
								matchMode = MatchMode.ANYWHERE;
							}
						} else {
							matchMode = MatchMode.ANYWHERE;
						}
						if (cond.getType().equalsIgnoreCase("like")) {
							criterionList.add(Restrictions.like(propertyName, value.toString(), matchMode));
						} else {
							criterionList.add(Restrictions.ilike(propertyName, value.toString(), matchMode));
						}
					} else if (cond.getType().equalsIgnoreCase("between")) {
						Object betweenValue = buildGetMethod(obj, cond.getBetweenProperty()).invoke(obj, new Object[0]);
						criterionList.add(Restrictions.between(propertyName, value, betweenValue));
					} else {
						criterionList.add(Restrictions.eq(propertyName, value));
					}
				}
			}
			return criterionList;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String buildGetMethodName(String propertyName) {
		return "get" + StringUtils.capitalize(propertyName);
	}

	public static String buildGetMethodField(String methodName) {
		return StringUtils.uncapitalize(methodName.substring(3));
	}

	public static <T> Method buildGetMethod(T entity, String propertyName) throws SecurityException, NoSuchMethodException {
		String get = buildGetMethodName(propertyName);
		Method getMethod = entity.getClass().getMethod(get, new Class[0]);
		return getMethod;
	}

	public static Map<String, Object> buildParameters(HttpServletRequest request, Object entity, Page page) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Map<String, String> orderMap = getOrder(request);
		try {

			String parameterStr = request.getParameter("queryConditions");
			List<Conditions> list = entityList(parameterStr, Conditions.class);
			if (list != null) {
				Iterator<Conditions> it = list.iterator();
				while (it.hasNext()) {
					Conditions conds = it.next();
					Condition cond = new Condition(conds.getCondition());
					Method getMethod = buildGetMethod(entity, cond.getValueProperty());
					Object value = getMethod.invoke(entity, new Object[0]);
					String columnName = getMethod.getAnnotation(Column.class).name();
					if (cond.getType().equalsIgnoreCase("like") || cond.getType().equalsIgnoreCase("ilike")) {
						paramMap.put(cond.getPropertyName(), "and " + cond.getTableAlias() + "." + columnName + " like '%" + value.toString() + "%'");
					} else {
						paramMap.put(cond.getPropertyName(), "and " + cond.getTableAlias() + "." + columnName + " = '" + value.toString() + "'");
					}
				}
			}

			if (orderMap != null) {
				paramMap.put("order_property", orderMap.get("property"));
				paramMap.put("order_direction", orderMap.get("direction"));
			}

			String nopage = request.getParameter("nopage") == null ? "" : request.getParameter("nopage");
			if (page != null && !nopage.equals("yes")) {
				paramMap.put("page_start", page.getStart());
				paramMap.put("page_limit", page.getLimit());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return paramMap;
	}
}

 

你可能感兴趣的:(反射)