excel导入导出工具类

maven配置

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
</dependency>

调用方式:

导出:

OutputStream out = xxxx;

List<String[]> headNames = new ArrayList<String[]>();
headNames.add(new String[] { "交易ID", "用户ID", "提现金额", "创建时间"});
List<String[]> fieldNames = new ArrayList<String[]>();
fieldNames.add(new String[] { "payid", "payAccountUid", "totalMoney", "createdAt"});

ExportSetInfo setInfo = new ExportSetInfo();
LinkedHashMap<String, List> objsMap = new LinkedHashMap<String, List>();
List<XwTrades> xwTradesList = xxxx;
objsMap.put("提现数据", xwTradesList);
setInfo.setObjsMap(objsMap);
setInfo.setFieldNames(fieldNames);
setInfo.setTitles(new String[] { "提现数据" });
setInfo.setHeadNames(headNames);
setInfo.setOut(out);

导入:

InputStream in = xxxx;

ExcelUtil excelUtil = new ExcelUtil();
List<String[]> dataList = excelUtil.importExcel(in, 0);

ExcelUtil:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;

public class ExcelUtil2
{
	private HSSFWorkbook wb;
	private BufferedInputStream in;

	private CellStyle titleStyle;        // 标题行样式
	private Font titleFont;              // 标题行字体        
	private CellStyle dateStyle;         // 日期行样式
	private Font dateFont;               // 日期行字体
	private CellStyle headStyle;         // 表头行样式
	private Font headFont;               // 表头行字体
	private CellStyle contentStyle ;     // 内容行样式
	private Font contentFont;            // 内容行字体
	private SimpleDateFormat sdf;
	
	
	/**
	 * 导出数据
	 * @param setInfo
	 * @throws IOException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings("unchecked")
	public void export2Excel(ExportSetInfo setInfo) throws IOException, IllegalArgumentException, IllegalAccessException
	{
		initWrite();
		initStyle(setInfo);
		sdf = new SimpleDateFormat(setInfo.getDateFormat());
		Set<Entry<String, List>> set = setInfo.getObjsMap().entrySet();
		String[] sheetNames = new String[setInfo.getObjsMap().size()];
		int sheetNameNum = 0;
		for (Entry<String, List> entry : set)
		{
			sheetNames[sheetNameNum] = entry.getKey();
			sheetNameNum++;
		}
		HSSFSheet[] sheets = getSheets(setInfo.getObjsMap().size(), sheetNames);
		int sheetNum = 0;
		for (Entry<String, List> entry : set)
		{
			int rowNum = 0;
			// Sheet
			List objs = entry.getValue();
			if(setInfo.isShowTableTitle()){
				// 标题行
				createTableTitleRow(setInfo, sheets, sheetNum, rowNum);
				rowNum++;
			}
			if(setInfo.isShowTableDate()){
				// 日期行
				createTableDateRow(setInfo, sheets, sheetNum, rowNum);
				rowNum++;
			}
			// 表头
			creatTableHeadRow(setInfo, sheets, sheetNum, rowNum);
			rowNum++;
			// 表体
			String[] fieldNames = setInfo.getFieldNames().get(sheetNum);
			int index = 0;
			for (Object obj : objs)
			{
				HSSFRow contentRow = sheets[sheetNum].createRow(rowNum);
				contentRow.setHeight((short) 300);
				HSSFCell[] cells = getCells(contentRow, setInfo.getFieldNames().get(sheetNum).length, index);
				int cellNum = 1; // 去掉一列序号,因此从1开始
				if(fieldNames != null)
				{
					for (int num = 0; num < fieldNames.length; num++)
					{
						Object value = ReflectionUtils.invokeGetterMethod(obj, fieldNames[num]);
						if(value instanceof Date){
							value = sdf.format(value);
						}
						cells[cellNum].setCellValue(value == null ? "" : value.toString());
						cellNum++;
					}
				}
				index++;
				rowNum++;
			}
			if(setInfo.isAutoAdjustColumnSize()){
				adjustColumnSize(sheets, sheetNum, fieldNames); // 自动调整列宽
			}
			sheetNum++;
		}
		wb.write(setInfo.getOut());
		closeWb();
	}
	
	/**
	 * 导入数据
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public Map<String, List<String[]>> importExcel(String filePath) throws IOException {
		return importExcel(new FileInputStream(filePath));
	}

	
	/**
	 * 导入数据
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public Map<String, List<String[]>> importExcel(InputStream inputStream) throws IOException {
		initReadWb(inputStream);
		Map<String, List<String[]>> map = getAllSheetValues(-1, -1);
		closeWb();
		return map;
	}
	
	/**
	 * 导入数据
	 * @param filePath
	 * @param sheetIndex
	 * @param rowNum
	 * @return
	 * @throws IOException
	 */
	public List<String[]> importExcel(String filePath, int sheetIndex, int rowNum) throws IOException {
		return importExcel(new FileInputStream(filePath), sheetIndex, rowNum);
	}
	
	/**
	 * 导入数据
	 * @param inputStream
	 * @param sheetIndex
	 * @param rowNum
	 * @return
	 * @throws IOException
	 */
	public List<String[]> importExcel(InputStream inputStream, int sheetIndex, int rowNum) throws IOException {
		initReadWb(inputStream);
		List<String[]> list = getOneSheetValues(sheetIndex, rowNum);
		closeWb();
		return list;
	}
	
	/**
	 * 导入数据
	 * @param filePath
	 * @param sheetIndex
	 * @return
	 * @throws IOException
	 */
	public List<String[]> importExcel(String filePath, int sheetIndex) throws IOException {
		return importExcel(new FileInputStream(filePath), sheetIndex);
	}
	
	/**
	 * 导入数据
	 * @param inputStream
	 * @param sheetIndex
	 * @return
	 * @throws IOException
	 */
	public List<String[]> importExcel(InputStream inputStream, int sheetIndex) throws IOException {
		initReadWb(inputStream);
		List<String[]> list = getOneSheetValues(sheetIndex, -1);
		closeWb();
		return list;
	}
	
	/**
	 * 初始化导出
	 */
	private void initWrite() 
	{
		wb = new HSSFWorkbook();
	}
	
	/**
	 * 初始化导入
	 * @param inputStream
	 * @throws IOException
	 */
	private void initReadWb(InputStream inputStream) throws IOException {
		in = new BufferedInputStream(inputStream);
		POIFSFileSystem fs = new POIFSFileSystem(in);
		wb = new HSSFWorkbook(fs);
	}
	
	/**
	 * 关闭IO
	 * @throws IOException
	 */
	private void closeWb() throws IOException {
		if(in != null){
			in.close();
		}
		if(wb != null){
			wb.close();
		}
	}
	
	/**
	 * 初始化样式
	 * @param setInfo
	 */
	private void initStyle(ExportSetInfo setInfo){
		titleFont = wb.createFont();
		dateFont = wb.createFont();
		headFont = wb.createFont();
		contentFont = wb.createFont();
		
		titleFont.setFontName("宋体");
		titleFont.setFontHeightInPoints((short) 20);
		titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		titleFont.setCharSet(Font.DEFAULT_CHARSET);
		titleFont.setColor(IndexedColors.BLACK.index);
		
		dateFont.setFontName("宋体");
		dateFont.setFontHeightInPoints((short) 10);
		dateFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		dateFont.setCharSet(Font.DEFAULT_CHARSET);
		dateFont.setColor(IndexedColors.BLACK.index);
		
		headFont.setFontName("宋体");
		headFont.setFontHeightInPoints((short) 10);
		headFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
		headFont.setCharSet(Font.DEFAULT_CHARSET);
		headFont.setColor(IndexedColors.BLACK.index);
		
		contentFont.setFontName("宋体");
		contentFont.setFontHeightInPoints((short) 10);
		contentFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
		contentFont.setCharSet(Font.DEFAULT_CHARSET);
		contentFont.setColor(IndexedColors.BLACK.index);
		
		if(setInfo.getTitleStyle() != null){
			titleStyle = setInfo.getTitleStyle();
		}else{
			titleStyle = wb.createCellStyle();
			titleStyle.setAlignment(CellStyle.ALIGN_CENTER);
			titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
			titleStyle.setFont(titleFont);
			titleStyle.setFillBackgroundColor(IndexedColors.BLACK.index);
		}
		
		if(setInfo.getDateStyle() != null){
			dateStyle = setInfo.getDateStyle();
		}else{
			dateStyle = wb.createCellStyle();
			dateStyle.setAlignment(CellStyle.ALIGN_CENTER_SELECTION);
			dateStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
			dateStyle.setFont(dateFont);
			dateStyle.setFillBackgroundColor(IndexedColors.BLACK.index);
		}
		
		if(setInfo.getHeadStyle() != null){
			headStyle = setInfo.getHeadStyle();
		}else{
			headStyle = wb.createCellStyle();
			headStyle.setAlignment(CellStyle.ALIGN_CENTER);
			headStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
			headStyle.setFont(headFont);
			headStyle.setFillBackgroundColor(IndexedColors.YELLOW.index);
			headStyle.setBorderTop(CellStyle.BORDER_MEDIUM);
			headStyle.setBorderBottom(CellStyle.BORDER_THIN);
			headStyle.setBorderLeft(CellStyle.BORDER_THIN);
			headStyle.setBorderRight(CellStyle.BORDER_THIN);
			headStyle.setTopBorderColor(IndexedColors.BLACK.index);
			headStyle.setBottomBorderColor(IndexedColors.BLACK.index);
			headStyle.setLeftBorderColor(IndexedColors.BLACK.index);
			headStyle.setRightBorderColor(IndexedColors.BLACK.index);
		}

		if(setInfo.getDateStyle() != null){
			contentStyle = setInfo.getDateStyle();
		}else{
			contentStyle = wb.createCellStyle();
			contentStyle.setAlignment(CellStyle.ALIGN_CENTER);
			contentStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
			contentStyle.setFont(contentFont);
			contentStyle.setBorderTop(CellStyle.BORDER_THIN);
			contentStyle.setBorderBottom(CellStyle.BORDER_THIN);
			contentStyle.setBorderLeft(CellStyle.BORDER_THIN);
			contentStyle.setBorderRight(CellStyle.BORDER_THIN);
			contentStyle.setTopBorderColor(IndexedColors.BLACK.index);
			contentStyle.setBottomBorderColor(IndexedColors.BLACK.index);
			contentStyle.setLeftBorderColor(IndexedColors.BLACK.index);
			contentStyle.setRightBorderColor(IndexedColors.BLACK.index);
			contentStyle.setWrapText(true); // 字段换行
		}
		
	}
	
	
	
	/**
	 *  自动调整列宽
	 */
	@SuppressWarnings("unused")
	private void adjustColumnSize(HSSFSheet[] sheets, int sheetNum, String[] fieldNames) 
	{
		for(int i = 0; i < fieldNames.length + 1; i++)
		{
			sheets[sheetNum].autoSizeColumn(i, true);
		}
	}

	/**
	 *  创建标题行(需合并单元格)
	 */
	private void createTableTitleRow(ExportSetInfo setInfo,
			HSSFSheet[] sheets, int sheetNum, int row)
	{
		CellRangeAddress titleRange = new CellRangeAddress(0, 0, 0, 
				setInfo.getFieldNames().get(sheetNum).length);
		sheets[sheetNum].addMergedRegion(titleRange);
		HSSFRow titleRow = sheets[sheetNum].createRow(row);
		titleRow.setHeight((short) 800);
		HSSFCell titleCell = titleRow.createCell(0);
		titleCell.setCellStyle(titleStyle);
		titleCell.setCellValue(setInfo.getTitles()[sheetNum]);
	}

	/**
	 *  创建日期行(需合并单元格)
	 */
	private void createTableDateRow(ExportSetInfo setInfo,
			HSSFSheet[] sheets, int sheetNum, int row)
	{
		CellRangeAddress dateRange = new CellRangeAddress(1, 1, 0, 
				setInfo.getFieldNames().get(sheetNum).length);
		sheets[sheetNum].addMergedRegion(dateRange);
		HSSFRow dateRow = sheets[sheetNum].createRow(row);
		dateRow.setHeight((short) 350);
		HSSFCell dateCell = dateRow.createCell(0);
		dateCell.setCellStyle(dateStyle);
		dateCell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
	}

	/**
	 *  创建表头行(需合并单元格)
	 */
	private void creatTableHeadRow(ExportSetInfo setInfo,
			HSSFSheet[] sheets, int sheetNum, int row)
	{
		// 表头
		HSSFRow headRow = sheets[sheetNum].createRow(row);
		headRow.setHeight((short) 350);
		// 序号列
		HSSFCell snCell = headRow.createCell(0);
		snCell.setCellStyle(headStyle);
		snCell.setCellValue("序号");
		// 列头名称
		for(int num = 1, len = setInfo.getHeadNames().get(sheetNum).length; num <= len; num++)
		{
			HSSFCell headCell = headRow.createCell(num);
			headCell.setCellStyle(headStyle);
			headCell.setCellValue(setInfo.getHeadNames().get(sheetNum)[num - 1]);
		}
	}

	/**
	 *  创建所有的Sheet
	 */
	private HSSFSheet[] getSheets(int num, String[] names)
	{
		HSSFSheet[] sheets = new HSSFSheet[num];
		for (int i = 0; i < num; i++)
		{
			sheets[i] = wb.createSheet(names[i]);
		}
		return sheets;
	}

	/**
	 *  创建内容行的每一列(附加一列序号)
	 */
	private HSSFCell[] getCells(HSSFRow contentRow, int num, int index)
	{
		HSSFCell[] cells = new HSSFCell[num + 1];

		for (int i = 0,len = cells.length; i < len; i++)
		{
			cells[i] = contentRow.createCell(i);
			cells[i].setCellStyle(contentStyle);
		}
		// 设置序号列值
		cells[0].setCellValue(index+1);

		return cells;
	}
	

	/**
	 *  封装Excel导出的设置信息
	 */
	public static class ExportSetInfo
	{
		@SuppressWarnings("unchecked")
		private LinkedHashMap<String, List> objsMap;

		private String[] titles;

		private List<String[]> headNames;

		private List<String[]> fieldNames;

		private OutputStream out;
		
		private String dateFormat = "yyyy-MM-dd HH:mm:ss";
		
		private CellStyle titleStyle;        // 标题行样式
		private CellStyle dateStyle;         // 日期行样式
		private CellStyle headStyle;         // 表头行样式
		private CellStyle contentStyle ;     // 内容行样式
		
		private boolean showTableTitle = false;
		private boolean showTableDate = false;
		private boolean autoAdjustColumnSize = true;

		@SuppressWarnings("unchecked")
		public LinkedHashMap<String, List> getObjsMap()
		{
			return objsMap;
		}

		/**
		 * @param objMap 导出数据
		 * 
		 * 泛型
		 * String : 代表sheet名称
		 * List : 代表单个sheet里的所有行数据
		 */
		@SuppressWarnings("unchecked")
		public void setObjsMap(LinkedHashMap<String, List> objsMap)
		{
			this.objsMap = objsMap;
		}

		public List<String[]> getFieldNames()
		{
			return fieldNames;
		}

		/**
		 * @param clazz 对应每个sheet里的每行数据的对象的属性名称
		 */
		public void setFieldNames(List<String[]> fieldNames)
		{
			this.fieldNames = fieldNames;
		}

		public String[] getTitles()
		{
			return titles;
		}

		/**
		 * @param titles 对应每个sheet里的标题,即顶部大字
		 */
		public void setTitles(String[] titles)
		{
			this.titles = titles;
		}

		public List<String[]> getHeadNames()
		{
			return headNames;
		}

		/**
		 * @param headNames 对应每个页签的表头的每一列的名称
		 */
		public void setHeadNames(List<String[]> headNames)
		{
			this.headNames = headNames;
		}

		public OutputStream getOut()
		{
			return out;
		}

		/**
		 * @param out Excel数据将输出到该输出流
		 */
		public void setOut(OutputStream out)
		{
			this.out = out;
		}

		public void setDateFormat(String dateFormat) {
			this.dateFormat = dateFormat;
		}

		public String getDateFormat() {
			return dateFormat;
		}

		public CellStyle getTitleStyle() {
			return titleStyle;
		}

		public void setTitleStyle(CellStyle titleStyle) {
			this.titleStyle = titleStyle;
		}


		public CellStyle getDateStyle() {
			return dateStyle;
		}

		public void setDateStyle(CellStyle dateStyle) {
			this.dateStyle = dateStyle;
		}

		public CellStyle getHeadStyle() {
			return headStyle;
		}

		public void setHeadStyle(CellStyle headStyle) {
			this.headStyle = headStyle;
		}

		public CellStyle getContentStyle() {
			return contentStyle;
		}

		public void setContentStyle(CellStyle contentStyle) {
			this.contentStyle = contentStyle;
		}

		public boolean isShowTableTitle() {
			return showTableTitle;
		}

		public void setShowTableTitle(boolean showTableTitle) {
			this.showTableTitle = showTableTitle;
		}
		
		public boolean isShowTableDate() {
			return showTableDate;
		}

		public void setShowTableDate(boolean showTableDate) {
			this.showTableDate = showTableDate;
		}

		public boolean isAutoAdjustColumnSize() {
			return autoAdjustColumnSize;
		}

		public void setAutoAdjustColumnSize(boolean autoAdjustColumnSize) {
			this.autoAdjustColumnSize = autoAdjustColumnSize;
		}
		
	}
	
	/**
	 * 获取单元格中的值
	 * 
	 * @param cell 单元格
	 * @return
	 */
	private static Object getCellValue(Cell cell) {
		int type = cell.getCellType();
		switch (type) {
		case Cell.CELL_TYPE_STRING:
			return (Object) cell.getStringCellValue();
		case Cell.CELL_TYPE_NUMERIC:
			Double value = cell.getNumericCellValue();
			return (Object) (value.intValue());
		case Cell.CELL_TYPE_BOOLEAN:
			return (Object) cell.getBooleanCellValue();
		case Cell.CELL_TYPE_FORMULA:
			return (Object) cell.getArrayFormulaRange().formatAsString();
		case Cell.CELL_TYPE_BLANK:
			return (Object) "";
		default:
			return null;
		}
	}
	
	/**
	 * 读取一个sheet的数据
	 * @param sheetIndex 从0开始
	 * @param rowNum 从0开始
	 * @return
	 * @throws IOException
	 */
	private List<String[]> getOneSheetValues(int sheetIndex, int rowNum) throws IOException{
		List<String[]> list = new ArrayList<String[]>();
		HSSFSheet sheet = wb.getSheetAt(sheetIndex);
		if(sheet == null){
			return list;
		}
		int maxColumnIndex = 0;
		int maxRow = sheet.getLastRowNum();
		List<HSSFRow> rowList = new ArrayList<HSSFRow>();
		if(rowNum >= 0){
			if(rowNum > maxRow){
				return list;
			}
			HSSFRow row = sheet.getRow(rowNum);
			maxColumnIndex = row.getLastCellNum();
			rowList.add(row);
		}else{
			for(int rowIndex=0; rowIndex<=maxRow; rowIndex++){
				HSSFRow row = sheet.getRow(rowIndex);
				if(maxColumnIndex == 0 || row.getLastCellNum() > maxColumnIndex){
					maxColumnIndex = row.getLastCellNum();
				}
				rowList.add(row);
			}
		}
		for(HSSFRow row : rowList){
			String[] arr = new String[maxColumnIndex];
			for(int columnIndex=0; columnIndex<maxColumnIndex; columnIndex++){
				HSSFCell cell = row.getCell(columnIndex);
				if(cell == null){
					arr[columnIndex] = "";
				}else{
					arr[columnIndex] = String.valueOf(getCellValue(cell));
				}
			}
			list.add(arr);
		}
		return list;
	}
	
	/**
	 * 读取所有sheet的数据
	 * @param file
	 * @param sheetIndex
	 * @param rowNum
	 * @return
	 * @throws IOException
	 */
	private Map<String, List<String[]>> getAllSheetValues(int sheetIndex, int rowNum) throws IOException{
		Map<String, List<String[]>> map = new LinkedHashMap<String, List<String[]>>();
		List<HSSFSheet> sheetList = new ArrayList<HSSFSheet>();
		if(sheetIndex >= 0){
			sheetList.add(wb.getSheetAt(sheetIndex));
		}else{
			for (int i = 0; i < wb.getNumberOfSheets(); i++) {
				sheetList.add(wb.getSheetAt(i));
			}
		}
             
		for(HSSFSheet st : sheetList){
			map.put(st.getSheetName(), getOneSheetValues(sheetIndex, rowNum));
		}
		return map;
	}
	
	/**
	 * 调整数据表头顺序
	 * @param baseObjsList
	 * @param destHearder
	 * @return
	 * @throws Exception
	 */
	public List<String[]> changeOrderByHeader(List<String[]> baseObjsList, String[] destHearder) throws Exception {
		String[] baseHearder = baseObjsList.get(0);
		if(destHearder.length != baseHearder.length){
			throw new Exception("表头匹配错误");
		}
		Map<String, Integer> baseHearderMap = new HashMap<String, Integer>();
		for(int i=0; i<baseHearder.length; i++){
			String h = baseHearder[i];
			baseHearderMap.put((String)h, i);
		}
		Map<Integer, Integer> orderMap = new HashMap<Integer, Integer>(); //key: destObjsList下标  -- baseObjsList下标
		for(int i=0; i<destHearder.length; i++){
			String h = destHearder[i];
			if(!baseHearderMap.containsKey(h)){
				throw new Exception("表头匹配错误,缺少["+h+"]列");
			}
			orderMap.put(i, baseHearderMap.get(h));
		}
		List<String[]> destObjsList = new ArrayList<String[]>();
		for(int i=0; i<baseObjsList.size(); i++){
			if(i == 0){
				continue;
			}
			String[] baseObjs = baseObjsList.get(i);
			String[] destObjs = new String[baseObjs.length];
			for(int j=0; j<baseObjs.length; j++){
				destObjs[j] = baseObjs[orderMap.get(j)];
			}
			destObjsList.add(destObjs);
		}
		return destObjsList;
	}
	
}

 

ReflectionUtils:

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 反射工具类.
 * 
 * 提供访问私有变量,获取泛型类型Class, 提取集合中元素的属性, 转换字符串到对象等Util函数.
 * 
 */
public class ReflectionUtils
{

	private static Log logger = LogFactory.getLog(ReflectionUtils.class);

	static
	{
		DateLocaleConverter dc = new DateLocaleConverter();
		// dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" });
		ConvertUtils.register(dc, Date.class);
	}

	/**
	 * 调用Getter方法.
	 */
	public static Object invokeGetterMethod(Object target, String propertyName)
	{
		String getterMethodName = "get" + StringUtils.capitalize(propertyName);
		return invokeMethod(target, getterMethodName, new Class[] {},
				new Object[] {});
	}

	/**
	 * 调用Setter方法.使用value的Class来查找Setter方法.
	 */
	public static void invokeSetterMethod(Object target, String propertyName,
			Object value)
	{
		invokeSetterMethod(target, propertyName, value, null);
	}

	/**
	 * 调用Setter方法.
	 * 
	 * @param propertyType 用于查找Setter方法,为空时使用value的Class替代.
	 */
	public static void invokeSetterMethod(Object target, String propertyName,
			Object value, Class<?> propertyType)
	{
		Class<?> type = propertyType != null ? propertyType : value.getClass();
		String setterMethodName = "set" + StringUtils.capitalize(propertyName);
		invokeMethod(target, setterMethodName, new Class[] { type },
				new Object[] { value });
	}

	/**
	 * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
	 */
	public static Object getFieldValue(final Object object,
			final String fieldName)
	{
		Field field = getDeclaredField(object, fieldName);

		if (field == null)
		{
			throw new IllegalArgumentException("Could not find field ["
					+ fieldName + "] on target [" + object + "]");
		}

		makeAccessible(field);

		Object result = null;
		try
		{
			result = field.get(object);
		}
		catch (IllegalAccessException e)
		{
			logger.error("不可能抛出的异常{}" + e.getMessage());
		}
		return result;
	}

	/**
	 * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
	 */
	public static void setFieldValue(final Object object,
			final String fieldName, final Object value)
	{
		Field field = getDeclaredField(object, fieldName);

		if (field == null)
		{
			throw new IllegalArgumentException("Could not find field ["
					+ fieldName + "] on target [" + object + "]");
		}

		makeAccessible(field);

		try
		{
			field.set(object, value);
		}
		catch (IllegalAccessException e)
		{
			logger.error("不可能抛出的异常:{}" + e.getMessage());
		}
	}

	/**
	 * 直接调用对象方法, 无视private/protected修饰符.
	 */
	public static Object invokeMethod(final Object object,
			final String methodName, final Class<?>[] parameterTypes,
			final Object[] parameters)
	{
		Method method = getDeclaredMethod(object, methodName, parameterTypes);
		if (method == null)
		{
			throw new IllegalArgumentException("Could not find method ["
					+ methodName + "] parameterType " + parameterTypes
					+ " on target [" + object + "]");
		}

		method.setAccessible(true);

		try
		{
			return method.invoke(object, parameters);
		}
		catch (Exception e)
		{
			throw convertReflectionExceptionToUnchecked(e);
		}
	}

	/**
	 * 循环向上转型, 获取对象的DeclaredField.
	 * 
	 * 如向上转型到Object仍无法找到, 返回null.
	 */
	protected static Field getDeclaredField(final Object object,
			final String fieldName)
	{
		if (object == null) {
			throw new IllegalArgumentException("object不能为空");
		}
		for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
				.getSuperclass())
		{
			try
			{
				return superClass.getDeclaredField(fieldName);
			}
			catch (NoSuchFieldException e)
			{// NOSONAR
				// Field不在当前类定义,继续向上转型
			}
		}
		return null;
	}

	/**
	 * 强行设置Field可访问.
	 */
	protected static void makeAccessible(final Field field)
	{
		if (!Modifier.isPublic(field.getModifiers())
				|| !Modifier.isPublic(field.getDeclaringClass().getModifiers()))
		{
			field.setAccessible(true);
		}
	}

	/**
	 * 循环向上转型, 获取对象的DeclaredMethod.
	 * 
	 * 如向上转型到Object仍无法找到, 返回null.
	 */
	protected static Method getDeclaredMethod(Object object, String methodName,
			Class<?>[] parameterTypes)
	{
		if (object == null) {
			throw new IllegalArgumentException("object不能为空");
		}
		for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
				.getSuperclass())
		{
			try
			{
				return superClass.getDeclaredMethod(methodName, parameterTypes);
			}
			catch (NoSuchMethodException e)
			{// NOSONAR
				// Method不在当前类定义,继续向上转型
			}
		}
		return null;
	}

	/**
	 * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. eg. public UserDao
	 * extends HibernateDao<User>
	 * 
	 * @param clazz The class to introspect
	 * @return the first generic declaration, or Object.class if cannot be
	 * determined
	 */
	@SuppressWarnings("unchecked")
	public static <T> Class<T> getSuperClassGenricType(final Class clazz)
	{
		return getSuperClassGenricType(clazz, 0);
	}

	/**
	 * 通过反射, 获得定义Class时声明的父类的泛型参数的类型. 如无法找到, 返回Object.class.
	 * 
	 * 如public UserDao extends HibernateDao<User,Long>
	 * 
	 * @param clazz clazz The class to introspect
	 * @param index the Index of the generic ddeclaration,start from 0.
	 * @return the index generic declaration, or Object.class if cannot be
	 * determined
	 */
	@SuppressWarnings("unchecked")
	public static Class getSuperClassGenricType(final Class clazz,
			final int index)
	{
		Type genType = clazz.getGenericSuperclass();

		if (!(genType instanceof ParameterizedType))
		{
			logger.warn(clazz.getSimpleName()
					+ "'s superclass not ParameterizedType");
			return Object.class;
		}

		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

		if (index >= params.length || index < 0)
		{
			logger.warn("Index: " + index + ", Size of "
					+ clazz.getSimpleName() + "'s Parameterized Type: "
					+ params.length);
			return Object.class;
		}
		if (!(params[index] instanceof Class))
		{
			logger
			.warn(clazz.getSimpleName()
					+ " not set the actual class on superclass generic parameter");
			return Object.class;
		}

		return (Class) params[index];
	}

	/**
	 * 提取集合中的对象的属性(通过getter函数), 组合成List.
	 * 
	 * @param collection 来源集合.
	 * @param propertyName 要提取的属性名.
	 */
	@SuppressWarnings("unchecked")
	public static List convertElementPropertyToList(
			final Collection collection, final String propertyName)
	{
		List list = new ArrayList();

		try
		{
			for (Object obj : collection)
			{
				list.add(PropertyUtils.getProperty(obj, propertyName));
			}
		}
		catch (Exception e)
		{
			throw convertReflectionExceptionToUnchecked(e);
		}

		return list;
	}

	/**
	 * 提取集合中的对象的属性(通过getter函数), 组合成由分割符分隔的字符串.
	 * 
	 * @param collection 来源集合.
	 * @param propertyName 要提取的属性名.
	 * @param separator 分隔符.
	 */
	@SuppressWarnings("unchecked")
	public static String convertElementPropertyToString(
			final Collection collection, final String propertyName,
			final String separator)
	{
		List list = convertElementPropertyToList(collection, propertyName);
		return StringUtils.join(list, separator);
	}

	/**
	 * 转换字符串到相应类型.
	 * 
	 * @param value 待转换的字符串
	 * @param toType 转换目标类型
	 */
	@SuppressWarnings("unchecked")
	public static <T> T convertStringToObject(String value, Class<T> toType)
	{
		try
		{
			return (T) ConvertUtils.convert(value, toType);
		}
		catch (Exception e)
		{
			throw convertReflectionExceptionToUnchecked(e);
		}
	}

	/**
	 * 将反射时的checked exception转换为unchecked exception.
	 */
	public static RuntimeException convertReflectionExceptionToUnchecked(
			Exception e)
	{
		return convertReflectionExceptionToUnchecked(null, e);
	}

	public static RuntimeException convertReflectionExceptionToUnchecked(
			String desc, Exception e)
	{
		desc = (desc == null) ? "Unexpected Checked Exception." : desc;
		if (e instanceof IllegalAccessException
				|| e instanceof IllegalArgumentException
				|| e instanceof NoSuchMethodException)
		{
			return new IllegalArgumentException(desc, e);
		}
		else if (e instanceof InvocationTargetException)
		{
			return new RuntimeException(desc, ((InvocationTargetException) e)
					.getTargetException());
		}
		else if (e instanceof RuntimeException)
		{
			return (RuntimeException) e;
		}
		return new RuntimeException(desc, e);
	}

	public static final <T> T getNewInstance(Class<T> cls)
	{
		try
		{
			return cls.newInstance();
		}
		catch (InstantiationException e)
		{
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 拷贝 source 指定的porperties 属性 到 dest中
	 * 
	 * @return void
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	public static void copyPorperties(Object dest, Object source,
			String[] porperties) throws InvocationTargetException,
	IllegalAccessException
	{
		for (String por : porperties)
		{
			Object srcObj = invokeGetterMethod(source, por);
			logger.debug("属性名:" + por + "------------- 属性值:" + srcObj);
			if (srcObj != null)
			{
				try
				{
					BeanUtils.setProperty(dest, por, srcObj);
				}
				catch (IllegalArgumentException e)
				{
					e.printStackTrace();
				}
				catch (IllegalAccessException e)
				{
					throw e;
				}
				catch (InvocationTargetException e)
				{
					throw e;
				}
			}
		}
	}

	/**
	 * 两者属性名一致时,拷贝source里的属性到dest里
	 * 
	 * @return void
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	@SuppressWarnings("unchecked")
	public static void copyPorperties(Object dest, Object source)
			throws IllegalAccessException, InvocationTargetException
	{
		Class srcCla = source.getClass();
		Field[] fsF = srcCla.getDeclaredFields();

		for (Field s : fsF)
		{
			String name = s.getName();
			Object srcObj = invokeGetterMethod(source, name);
			try
			{
				BeanUtils.setProperty(dest, name, srcObj);
			}
			catch (IllegalArgumentException e)
			{
				e.printStackTrace();
			}
			catch (IllegalAccessException e)
			{
				throw e;
			}
			catch (InvocationTargetException e)
			{
				throw e;
			}
		}
		// BeanUtils.copyProperties(dest, orig);
	}

}

  

 

posted @ 2016-04-26 18:04  圣雄1990  阅读(325)  评论(0编辑  收藏  举报