package org.bench4q.web.service;

import java.lang.reflect.Field;
import java.util.List;

import org.apache.log4j.Logger;
import org.bench4q.share.helper.ExceptionLog;
import org.bench4q.web.model.ResultModel;

public class ChangeToResultModel {
	public static ResultModel getResultModel(Object object,
			List<String> fieldNames) throws NoSuchFieldException {
		ResultModel resultModel = new ResultModel();

		for (String fieldName : fieldNames) {
			resultModel.setData(getSpecificFieldValue(object, fieldName));
		}

		return resultModel;
	}

	private static Object getSpecificFieldValue(Object object, String fieldName)
			throws NoSuchFieldException {
		try {
			Field field = getFieldAndSetAccessible(object, fieldName);
			return field.get(object);
		} catch (Exception e) {
			Logger.getLogger(ChangeToResultModel.class).info(
					ExceptionLog.getStackTrace(e));
			throw new NoSuchFieldException();
		}
	}

	private static Field getFieldAndSetAccessible(Object object,
			String fieldName) throws NoSuchFieldException, SecurityException {
		Field field = object.getClass().getDeclaredField(fieldName);
		field.setAccessible(true);
		return field;
	}

}
