ReportRelatedUtils.java 1.75 KB
package com.bsth.util;

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

import com.bsth.entity.Line;

public class ReportRelatedUtils {
	public static void main(String[] args) {
		try {
			ReportRelatedUtils test = new ReportRelatedUtils();
			Line line = new Line();
			line.setId(10);
			line.setName("abc");
			test.getValue(line, "name");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 通过字段名取到对象中该字段的相应值
	 * 
	 * @param t
	 *            对象
	 * @param fieldName
	 *            字段名
	 * @return
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 * @throws NoSuchFieldException
	 */
	public <T> Object getValue(T t, String fieldName)
			throws ClassNotFoundException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException,
			NoSuchFieldException {
		Object value = "";
		String tmpFieldName = firstCharToUpperCase(fieldName);
		Method method = null;
		try {
			method = t.getClass().getMethod("get" + tmpFieldName);
			value = method.invoke(t);
		} catch (NoSuchMethodException e) {
			if(method == null){
				method = t.getClass().getMethod("get" + tmpFieldName);
			}
			value = method.invoke(t);
			return value;
		}
		return value;
	}

	/**
	 * 首字母大写
	 * 
	 * @param source
	 *            源字符串
	 * @return
	 */
	private String firstCharToUpperCase(String source) {
		char[] arr = source.toCharArray();
		if (arr[1] >= 'A' && arr[1] <= 'Z') {
			return source;
		}else{
			if (arr[0] >= 'a' && arr[0] <= 'z') {
				arr[0] -= 'a' - 'A';
			}
		}
		return new String(arr);
	}
}