关于反射的小问题

平菇虾饺 2014-02-21 07:29:48
这两天无聊,想做一个打包Excel的小插件。

思路是这样的:

一、给出一个List<Model>,
二、遍历list逐个得到model。
三、通过反射获取model中变量名、public的getXXX方法。
四、写入Excel。

但是这儿出了一个很大的问题:

反射时得到的mothod.invoke(Object)方法Object必须实例化,也就是说其中肯定不可能有数据!

我就不明白怎么整了,问了一些人表示这个不可能。

我的理解大概是这样的、

能得到Class的各种信息相当于类对象在内存里面的位置已经显式的存在了。
List中的每个Model里面的数据应该也是能提取得到的,但是我就是不知道怎么整。
...全文
631 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
momoaiyanzi 2014-03-11
  • 打赏
  • 举报
回复
做excel的时候,我也是用反射做的。我多传了一些参数,用来指定需要的字段,excel 单元格大小等。
平菇虾饺 2014-03-11
  • 打赏
  • 举报
回复
引用 14 楼 ayong95 的回复:
[quote=引用 13 楼 qyp199312 的回复:] [quote=引用 10 楼 abstruct 的回复:] 给你一段写的代码,看你能理解不 [code=java [/code]
大哥“不能理解“就严重了哈,不过很感谢你写了这么长的代码来给我看。大体实现方法我看楼上一二层已经看明白了。这会我就写一个测试用例来。[/quote] 这不是实现了所有功能了吗?楼主你仔细认真看看哦。[/quote] 这倒是,不过既然已经能够获取了数据了,编写Excel不就很简单得么,,,倒是谢谢你写了这么多了。 我倒是有一个疑问。 反射可以动态的获取内存里面的数据(当然得在访问修饰符的范围之内) 动态代理可以把人家的数据全部拿过来-----具体意思大概是这个样子的: 把自己的CLASS放到人家正在运行的工程上面去,(大约可以查看8080之内的)。 启动自己的CLss. 显然得到人家的运行所有文件信息。 此时修改自己的源码,将他的服务给代理过来,再加一些奇奇怪怪的东西。 甚至,直接获取他正在运行的数据。 这些都是有理论基础了的呀! 这样不就显得不安全了么
平菇虾饺 2014-03-10
  • 打赏
  • 举报
回复
引用 10 楼 abstruct 的回复:
给你一段写的代码,看你能理解不

package com.poi.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelHeaderTitle {
	String name();
	int index();
	int colSpan() default 1;
	boolean export();
}


package com.poi.export;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;

import com.poi.annotation.ExcelHeaderTitle;
import com.poi.bean.TestBean;

public class ExcelExporter {

	public static void main(String[] args) throws Exception {
		FileOutputStream out = new FileOutputStream("G:\\test.xls");
		ExcelExporter ex = new ExcelExporter();
		List<TestBean> testBeans = new ArrayList<TestBean>();
		TestBean tb = new TestBean();
		tb.setAge(10);
		tb.setName("张三");
		tb.setSex("男");
		testBeans.add(tb);
		ex.export(TestBean.class, testBeans, "测试", out);
	}
	
	private ExcelColumn curColumn;

	public <E> void export(Class<E> clazz, List<E> datas, String sheetname, OutputStream out) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet(sheetname);
		int startRow = exportHeader(workbook, sheet, clazz);
		if (datas != null && !datas.isEmpty()) {
			exprotData(datas, workbook, sheet, startRow);
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private <E> void exprotData(List<E> datas, HSSFWorkbook workbook, HSSFSheet sheet, int rowIndex){
		ExcelColumn ec = curColumn;
		if(ec != null){
			while(ec.getChild() != null){
				ec = ec.getChild();
			}
			// 生成一个样式
			HSSFCellStyle style = workbook.createCellStyle();
			// 设置这些样式
			style.setFillForegroundColor(HSSFColor.WHITE.index);
			style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
			style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
			style.setBorderRight(HSSFCellStyle.BORDER_THIN);
			style.setBorderTop(HSSFCellStyle.BORDER_THIN);
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			// 字体
			HSSFFont font = workbook.createFont();
			font.setColor(HSSFColor.BLACK.index);
			font.setFontHeightInPoints((short) 10);
			font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
	
			style.setFont(font);
			for(E e : datas){
				List<ExcelColumnSingle> singles = ec.getColumns();
				HSSFRow row = sheet.createRow(rowIndex);
				if(singles != null){
					for (ExcelColumnSingle single : singles) {
						HSSFCell cell = row.createCell(single.getIndex());
						try {
							Object value = e.getClass().getMethod(single.getGetMethodName(), new Class[]{}).invoke(e, new Object[]{});
							String strVal = "";
							if(value != null){
								strVal = value.toString();
							}
							HSSFRichTextString text = new HSSFRichTextString(strVal);
							cell.setCellValue(text);
						} catch (Exception e1) {
						}
						int colSpan = single.getColSpan();
						if (colSpan > 1) {
							CellRangeAddress cra = new CellRangeAddress(rowIndex, rowIndex, single.getIndex(), single.getIndex() + colSpan - 1);
							setRegionBorder(HSSFCellStyle.BORDER_THIN, cra, sheet, workbook);
							sheet.addMergedRegion(cra);
						}
					}
				}
				rowIndex++;
			}
		}
	}

	/**
	 * <h4>方法说明:解析数据实体对象,找出需要导出的列,以及顺序</h4>
	 * 
	 * @param clazz
	 * @return List<ExcelColumn>
	 */
	private <E> ExcelColumn parseBean(Class<E> clazz, ExcelColumn ec) {
		ExcelColumn parent = new ExcelColumn();
		ExcelColumn child = ec;
		parent.setChild(child);
		Field[] fields = clazz.getDeclaredFields();
		List<ExcelColumnSingle> columns = new ArrayList<ExcelExporter.ExcelColumnSingle>();
		if (fields != null) {
			parent.setColumns(columns);
			for (Field field : fields) {
				// 如果有ExcelHeaderTitle注解
				if (field.isAnnotationPresent(ExcelHeaderTitle.class)) {
					ExcelHeaderTitle title = field.getAnnotation(ExcelHeaderTitle.class);
					String name = title.name();
					int index = title.index();
					int colSpan = title.colSpan();
					boolean export = title.export();
					if (export) {
						ExcelColumnSingle column = new ExcelExporter.ExcelColumnSingle();
						column.setName(name);
						column.setIndex(index);
						column.setColSpan(colSpan);
						String fieldName = field.getName();
						String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
						column.setGetMethodName(getMethodName);
						columns.add(column);
					}
				}
			}
		}
		Class<?> superClass = clazz.getSuperclass();
		if (superClass != Object.class) {
			parent = parseBean(superClass, parent);
		}
		return parent;
	}

	private <E> int exportHeader(HSSFWorkbook workbook, HSSFSheet sheet, Class<E> clazz) {
		// 生成一个样式
		HSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 字体
		HSSFFont font = workbook.createFont();
		font.setColor(HSSFColor.BLACK.index);
		font.setFontHeightInPoints((short) 12);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

		style.setFont(font);

		ExcelColumn column = parseBean(clazz, null);
		curColumn = column;
		int rowIndex = 0;
		while (column != null) {
			List<ExcelColumnSingle> singles = column.getColumns();
			if (column.getColumns() != null && !column.getColumns().isEmpty()) {
				HSSFRow row = sheet.createRow(rowIndex);
				for (ExcelColumnSingle single : singles) {
					HSSFCell cell = row.createCell(single.getIndex());
					cell.setCellStyle(style);
					HSSFRichTextString text = new HSSFRichTextString(single.getName());
					cell.setCellValue(text);
					int colSpan = single.getColSpan();
					if (colSpan > 1) {
						CellRangeAddress cra = new CellRangeAddress(rowIndex, rowIndex, single.getIndex(), single.getIndex() + colSpan - 1);
						setRegionBorder(HSSFCellStyle.BORDER_THIN, cra, sheet, workbook);
						sheet.addMergedRegion(cra);
					}
				}
				rowIndex++;
			}
			column = column.getChild();
		}

		return rowIndex;
	}

	private void setRegionBorder(int border, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook wb) {
		RegionUtil.setBorderBottom(border, region, sheet, wb);
		RegionUtil.setBorderLeft(border, region, sheet, wb);
		RegionUtil.setBorderRight(border, region, sheet, wb);
		RegionUtil.setBorderTop(border, region, sheet, wb);
	}

	class ExcelColumn {
		private ExcelColumn child;
		private List<ExcelColumnSingle> columns;
		private int level = 0;

		public ExcelColumn getChild() {
			return child;
		}

		public void setChild(ExcelColumn child) {
			if (child != null) {
				child.setLevel(child.getLevel() + 1);
			}
			this.child = child;
		}

		public List<ExcelColumnSingle> getColumns() {
			return columns;
		}

		public void setColumns(List<ExcelColumnSingle> columns) {
			this.columns = columns;
		}

		public void addExcelColumnSingle(ExcelColumnSingle column) {
			columns.add(column);
		}

		public int getLevel() {
			return level;
		}

		public void setLevel(int level) {
			this.level = level;
		}
	}

	class ExcelColumnSingle {
		private String name;
		private int index;
		private int colSpan;
		private String getMethodName;
		
		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getIndex() {
			return index;
		}

		public void setIndex(int index) {
			this.index = index;
		}

		public int getColSpan() {
			return colSpan;
		}

		public void setColSpan(int colSpan) {
			this.colSpan = colSpan;
		}

		public String getGetMethodName() {
			return getMethodName;
		}

		public void setGetMethodName(String getMethodName) {
			this.getMethodName = getMethodName;
		}

	}
}


package com.poi.bean;

import com.poi.annotation.ExcelHeaderTitle;

public class TestBean extends TestBeanBase{
	
	@ExcelHeaderTitle(name="姓名", index=0, export=true)
	private String name;
	
	@ExcelHeaderTitle(name="性别", index=1, export=true)
	private String sex;
	
	@ExcelHeaderTitle(name="年龄", index=2, export=true)
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
}


package com.poi.bean;

import com.poi.annotation.ExcelHeaderTitle;

public class TestBeanBase {

	@ExcelHeaderTitle(name="标题测试", index=0, colSpan=3, export=true)
	private String title;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
	
}

大哥“不能理解“就严重了哈,不过很感谢你写了这么长的代码来给我看。大体实现方法我看楼上一二层已经看明白了。这会我就写一个测试用例来。
平菇虾饺 2014-03-10
  • 打赏
  • 举报
回复
引用 8 楼 java_liyi 的回复:
还是没看懂lz要做什么,是要将类里面的字段 getXXX方法呢 存到excel里面呢 还是要反射获取对象属性的值呢

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


public class A {
	
	
	private String id;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public A(String s){
		this.id = s;
	}
	
	
	public static void main(String[] args) {
		//反射获取方法
		Method[] ms = A.class.getDeclaredMethods();//
		for(Method m:ms){
			System.out.println(m.getName());
		}
		//反射获取属性
		Field[] fs = A.class.getDeclaredFields();
		for(Field f : fs){
			System.out.println(f.getName());
		}
		//反射获取构造函数
		Constructor[] cs = A.class.getConstructors();
		for(Constructor c : cs){
			System.out.println(c.getName());
		}
		
		//先初始化
		List<A> l = init();
		//反射获取属性的值
		for(A a : l){
			for(Field f : a.getClass().getDeclaredFields()){
				try {
					System.out.println(f.getName()+":"+f.get(a));//可以看做在此写入Excel
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
	}
	
	public static List<A> init(){
		List<A> l = new ArrayList<A>();
		for(int i = 0;i<100;i++){
			l.add(new A(i+""));
		}
		return l;
	}
}

这种?
这种方法很不错的。刚好再加修改就可以取的传来List的值了。算是楼上那版的升级版。谢谢了哈! m.invoke(t.newInstance())
平菇虾饺 2014-03-10
  • 打赏
  • 举报
回复
引用 7 楼 shaguaanfanga 的回复:
public class Test {
	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		List<Model> list = new ArrayList<Model>();
		for (int i = 0; i < 10; i++) {
			list.add(new Model("model"+i));
		}
		
		Method[] methods = Model.class.getMethods();
		for (Model model : list) {
			for (Method method : methods) {
				if(method.getName().equalsIgnoreCase("getName")){
					System.out.println(method.invoke(model));
				}
			}
		}
	}

}
class Model{
	private String name;
	
	public Model(){
	}
	public Model(String name){
		this.name = name;
	}
	

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}
希望能帮到你
非常感谢你的帮助。我以前的错误在于我用了这个: m.invoke(t.newInstance()) 这样的话无论如何他都不会有新的数据出现了,,,还有一个更好的方法可以看楼下
ayong95 2014-03-10
  • 打赏
  • 举报
回复
引用 13 楼 qyp199312 的回复:
[quote=引用 10 楼 abstruct 的回复:] 给你一段写的代码,看你能理解不

package com.poi.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelHeaderTitle {
	String name();
	int index();
	int colSpan() default 1;
	boolean export();
}


package com.poi.export;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;

import com.poi.annotation.ExcelHeaderTitle;
import com.poi.bean.TestBean;

public class ExcelExporter {

	public static void main(String[] args) throws Exception {
		FileOutputStream out = new FileOutputStream("G:\\test.xls");
		ExcelExporter ex = new ExcelExporter();
		List<TestBean> testBeans = new ArrayList<TestBean>();
		TestBean tb = new TestBean();
		tb.setAge(10);
		tb.setName("张三");
		tb.setSex("男");
		testBeans.add(tb);
		ex.export(TestBean.class, testBeans, "测试", out);
	}
	
	private ExcelColumn curColumn;

	public <E> void export(Class<E> clazz, List<E> datas, String sheetname, OutputStream out) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet(sheetname);
		int startRow = exportHeader(workbook, sheet, clazz);
		if (datas != null && !datas.isEmpty()) {
			exprotData(datas, workbook, sheet, startRow);
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private <E> void exprotData(List<E> datas, HSSFWorkbook workbook, HSSFSheet sheet, int rowIndex){
		ExcelColumn ec = curColumn;
		if(ec != null){
			while(ec.getChild() != null){
				ec = ec.getChild();
			}
			// 生成一个样式
			HSSFCellStyle style = workbook.createCellStyle();
			// 设置这些样式
			style.setFillForegroundColor(HSSFColor.WHITE.index);
			style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
			style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
			style.setBorderRight(HSSFCellStyle.BORDER_THIN);
			style.setBorderTop(HSSFCellStyle.BORDER_THIN);
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			// 字体
			HSSFFont font = workbook.createFont();
			font.setColor(HSSFColor.BLACK.index);
			font.setFontHeightInPoints((short) 10);
			font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
	
			style.setFont(font);
			for(E e : datas){
				List<ExcelColumnSingle> singles = ec.getColumns();
				HSSFRow row = sheet.createRow(rowIndex);
				if(singles != null){
					for (ExcelColumnSingle single : singles) {
						HSSFCell cell = row.createCell(single.getIndex());
						try {
							Object value = e.getClass().getMethod(single.getGetMethodName(), new Class[]{}).invoke(e, new Object[]{});
							String strVal = "";
							if(value != null){
								strVal = value.toString();
							}
							HSSFRichTextString text = new HSSFRichTextString(strVal);
							cell.setCellValue(text);
						} catch (Exception e1) {
						}
						int colSpan = single.getColSpan();
						if (colSpan > 1) {
							CellRangeAddress cra = new CellRangeAddress(rowIndex, rowIndex, single.getIndex(), single.getIndex() + colSpan - 1);
							setRegionBorder(HSSFCellStyle.BORDER_THIN, cra, sheet, workbook);
							sheet.addMergedRegion(cra);
						}
					}
				}
				rowIndex++;
			}
		}
	}

	/**
	 * <h4>方法说明:解析数据实体对象,找出需要导出的列,以及顺序</h4>
	 * 
	 * @param clazz
	 * @return List<ExcelColumn>
	 */
	private <E> ExcelColumn parseBean(Class<E> clazz, ExcelColumn ec) {
		ExcelColumn parent = new ExcelColumn();
		ExcelColumn child = ec;
		parent.setChild(child);
		Field[] fields = clazz.getDeclaredFields();
		List<ExcelColumnSingle> columns = new ArrayList<ExcelExporter.ExcelColumnSingle>();
		if (fields != null) {
			parent.setColumns(columns);
			for (Field field : fields) {
				// 如果有ExcelHeaderTitle注解
				if (field.isAnnotationPresent(ExcelHeaderTitle.class)) {
					ExcelHeaderTitle title = field.getAnnotation(ExcelHeaderTitle.class);
					String name = title.name();
					int index = title.index();
					int colSpan = title.colSpan();
					boolean export = title.export();
					if (export) {
						ExcelColumnSingle column = new ExcelExporter.ExcelColumnSingle();
						column.setName(name);
						column.setIndex(index);
						column.setColSpan(colSpan);
						String fieldName = field.getName();
						String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
						column.setGetMethodName(getMethodName);
						columns.add(column);
					}
				}
			}
		}
		Class<?> superClass = clazz.getSuperclass();
		if (superClass != Object.class) {
			parent = parseBean(superClass, parent);
		}
		return parent;
	}

	private <E> int exportHeader(HSSFWorkbook workbook, HSSFSheet sheet, Class<E> clazz) {
		// 生成一个样式
		HSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 字体
		HSSFFont font = workbook.createFont();
		font.setColor(HSSFColor.BLACK.index);
		font.setFontHeightInPoints((short) 12);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

		style.setFont(font);

		ExcelColumn column = parseBean(clazz, null);
		curColumn = column;
		int rowIndex = 0;
		while (column != null) {
			List<ExcelColumnSingle> singles = column.getColumns();
			if (column.getColumns() != null && !column.getColumns().isEmpty()) {
				HSSFRow row = sheet.createRow(rowIndex);
				for (ExcelColumnSingle single : singles) {
					HSSFCell cell = row.createCell(single.getIndex());
					cell.setCellStyle(style);
					HSSFRichTextString text = new HSSFRichTextString(single.getName());
					cell.setCellValue(text);
					int colSpan = single.getColSpan();
					if (colSpan > 1) {
						CellRangeAddress cra = new CellRangeAddress(rowIndex, rowIndex, single.getIndex(), single.getIndex() + colSpan - 1);
						setRegionBorder(HSSFCellStyle.BORDER_THIN, cra, sheet, workbook);
						sheet.addMergedRegion(cra);
					}
				}
				rowIndex++;
			}
			column = column.getChild();
		}

		return rowIndex;
	}

	private void setRegionBorder(int border, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook wb) {
		RegionUtil.setBorderBottom(border, region, sheet, wb);
		RegionUtil.setBorderLeft(border, region, sheet, wb);
		RegionUtil.setBorderRight(border, region, sheet, wb);
		RegionUtil.setBorderTop(border, region, sheet, wb);
	}

	class ExcelColumn {
		private ExcelColumn child;
		private List<ExcelColumnSingle> columns;
		private int level = 0;

		public ExcelColumn getChild() {
			return child;
		}

		public void setChild(ExcelColumn child) {
			if (child != null) {
				child.setLevel(child.getLevel() + 1);
			}
			this.child = child;
		}

		public List<ExcelColumnSingle> getColumns() {
			return columns;
		}

		public void setColumns(List<ExcelColumnSingle> columns) {
			this.columns = columns;
		}

		public void addExcelColumnSingle(ExcelColumnSingle column) {
			columns.add(column);
		}

		public int getLevel() {
			return level;
		}

		public void setLevel(int level) {
			this.level = level;
		}
	}

	class ExcelColumnSingle {
		private String name;
		private int index;
		private int colSpan;
		private String getMethodName;
		
		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getIndex() {
			return index;
		}

		public void setIndex(int index) {
			this.index = index;
		}

		public int getColSpan() {
			return colSpan;
		}

		public void setColSpan(int colSpan) {
			this.colSpan = colSpan;
		}

		public String getGetMethodName() {
			return getMethodName;
		}

		public void setGetMethodName(String getMethodName) {
			this.getMethodName = getMethodName;
		}

	}
}


package com.poi.bean;

import com.poi.annotation.ExcelHeaderTitle;

public class TestBean extends TestBeanBase{
	
	@ExcelHeaderTitle(name="姓名", index=0, export=true)
	private String name;
	
	@ExcelHeaderTitle(name="性别", index=1, export=true)
	private String sex;
	
	@ExcelHeaderTitle(name="年龄", index=2, export=true)
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
}


package com.poi.bean;

import com.poi.annotation.ExcelHeaderTitle;

public class TestBeanBase {

	@ExcelHeaderTitle(name="标题测试", index=0, colSpan=3, export=true)
	private String title;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
	
}

大哥“不能理解“就严重了哈,不过很感谢你写了这么长的代码来给我看。大体实现方法我看楼上一二层已经看明白了。这会我就写一个测试用例来。[/quote] 这不是实现了所有功能了吗?楼主你仔细认真看看哦。
安特矮油 2014-03-06
  • 打赏
  • 举报
回复
给你一段写的代码,看你能理解不

package com.poi.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelHeaderTitle {
	String name();
	int index();
	int colSpan() default 1;
	boolean export();
}


package com.poi.export;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;

import com.poi.annotation.ExcelHeaderTitle;
import com.poi.bean.TestBean;

public class ExcelExporter {

	public static void main(String[] args) throws Exception {
		FileOutputStream out = new FileOutputStream("G:\\test.xls");
		ExcelExporter ex = new ExcelExporter();
		List<TestBean> testBeans = new ArrayList<TestBean>();
		TestBean tb = new TestBean();
		tb.setAge(10);
		tb.setName("张三");
		tb.setSex("男");
		testBeans.add(tb);
		ex.export(TestBean.class, testBeans, "测试", out);
	}
	
	private ExcelColumn curColumn;

	public <E> void export(Class<E> clazz, List<E> datas, String sheetname, OutputStream out) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet(sheetname);
		int startRow = exportHeader(workbook, sheet, clazz);
		if (datas != null && !datas.isEmpty()) {
			exprotData(datas, workbook, sheet, startRow);
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private <E> void exprotData(List<E> datas, HSSFWorkbook workbook, HSSFSheet sheet, int rowIndex){
		ExcelColumn ec = curColumn;
		if(ec != null){
			while(ec.getChild() != null){
				ec = ec.getChild();
			}
			// 生成一个样式
			HSSFCellStyle style = workbook.createCellStyle();
			// 设置这些样式
			style.setFillForegroundColor(HSSFColor.WHITE.index);
			style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
			style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
			style.setBorderRight(HSSFCellStyle.BORDER_THIN);
			style.setBorderTop(HSSFCellStyle.BORDER_THIN);
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			// 字体
			HSSFFont font = workbook.createFont();
			font.setColor(HSSFColor.BLACK.index);
			font.setFontHeightInPoints((short) 10);
			font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
	
			style.setFont(font);
			for(E e : datas){
				List<ExcelColumnSingle> singles = ec.getColumns();
				HSSFRow row = sheet.createRow(rowIndex);
				if(singles != null){
					for (ExcelColumnSingle single : singles) {
						HSSFCell cell = row.createCell(single.getIndex());
						try {
							Object value = e.getClass().getMethod(single.getGetMethodName(), new Class[]{}).invoke(e, new Object[]{});
							String strVal = "";
							if(value != null){
								strVal = value.toString();
							}
							HSSFRichTextString text = new HSSFRichTextString(strVal);
							cell.setCellValue(text);
						} catch (Exception e1) {
						}
						int colSpan = single.getColSpan();
						if (colSpan > 1) {
							CellRangeAddress cra = new CellRangeAddress(rowIndex, rowIndex, single.getIndex(), single.getIndex() + colSpan - 1);
							setRegionBorder(HSSFCellStyle.BORDER_THIN, cra, sheet, workbook);
							sheet.addMergedRegion(cra);
						}
					}
				}
				rowIndex++;
			}
		}
	}

	/**
	 * <h4>方法说明:解析数据实体对象,找出需要导出的列,以及顺序</h4>
	 * 
	 * @param clazz
	 * @return List<ExcelColumn>
	 */
	private <E> ExcelColumn parseBean(Class<E> clazz, ExcelColumn ec) {
		ExcelColumn parent = new ExcelColumn();
		ExcelColumn child = ec;
		parent.setChild(child);
		Field[] fields = clazz.getDeclaredFields();
		List<ExcelColumnSingle> columns = new ArrayList<ExcelExporter.ExcelColumnSingle>();
		if (fields != null) {
			parent.setColumns(columns);
			for (Field field : fields) {
				// 如果有ExcelHeaderTitle注解
				if (field.isAnnotationPresent(ExcelHeaderTitle.class)) {
					ExcelHeaderTitle title = field.getAnnotation(ExcelHeaderTitle.class);
					String name = title.name();
					int index = title.index();
					int colSpan = title.colSpan();
					boolean export = title.export();
					if (export) {
						ExcelColumnSingle column = new ExcelExporter.ExcelColumnSingle();
						column.setName(name);
						column.setIndex(index);
						column.setColSpan(colSpan);
						String fieldName = field.getName();
						String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
						column.setGetMethodName(getMethodName);
						columns.add(column);
					}
				}
			}
		}
		Class<?> superClass = clazz.getSuperclass();
		if (superClass != Object.class) {
			parent = parseBean(superClass, parent);
		}
		return parent;
	}

	private <E> int exportHeader(HSSFWorkbook workbook, HSSFSheet sheet, Class<E> clazz) {
		// 生成一个样式
		HSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 字体
		HSSFFont font = workbook.createFont();
		font.setColor(HSSFColor.BLACK.index);
		font.setFontHeightInPoints((short) 12);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

		style.setFont(font);

		ExcelColumn column = parseBean(clazz, null);
		curColumn = column;
		int rowIndex = 0;
		while (column != null) {
			List<ExcelColumnSingle> singles = column.getColumns();
			if (column.getColumns() != null && !column.getColumns().isEmpty()) {
				HSSFRow row = sheet.createRow(rowIndex);
				for (ExcelColumnSingle single : singles) {
					HSSFCell cell = row.createCell(single.getIndex());
					cell.setCellStyle(style);
					HSSFRichTextString text = new HSSFRichTextString(single.getName());
					cell.setCellValue(text);
					int colSpan = single.getColSpan();
					if (colSpan > 1) {
						CellRangeAddress cra = new CellRangeAddress(rowIndex, rowIndex, single.getIndex(), single.getIndex() + colSpan - 1);
						setRegionBorder(HSSFCellStyle.BORDER_THIN, cra, sheet, workbook);
						sheet.addMergedRegion(cra);
					}
				}
				rowIndex++;
			}
			column = column.getChild();
		}

		return rowIndex;
	}

	private void setRegionBorder(int border, CellRangeAddress region, HSSFSheet sheet, HSSFWorkbook wb) {
		RegionUtil.setBorderBottom(border, region, sheet, wb);
		RegionUtil.setBorderLeft(border, region, sheet, wb);
		RegionUtil.setBorderRight(border, region, sheet, wb);
		RegionUtil.setBorderTop(border, region, sheet, wb);
	}

	class ExcelColumn {
		private ExcelColumn child;
		private List<ExcelColumnSingle> columns;
		private int level = 0;

		public ExcelColumn getChild() {
			return child;
		}

		public void setChild(ExcelColumn child) {
			if (child != null) {
				child.setLevel(child.getLevel() + 1);
			}
			this.child = child;
		}

		public List<ExcelColumnSingle> getColumns() {
			return columns;
		}

		public void setColumns(List<ExcelColumnSingle> columns) {
			this.columns = columns;
		}

		public void addExcelColumnSingle(ExcelColumnSingle column) {
			columns.add(column);
		}

		public int getLevel() {
			return level;
		}

		public void setLevel(int level) {
			this.level = level;
		}
	}

	class ExcelColumnSingle {
		private String name;
		private int index;
		private int colSpan;
		private String getMethodName;
		
		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getIndex() {
			return index;
		}

		public void setIndex(int index) {
			this.index = index;
		}

		public int getColSpan() {
			return colSpan;
		}

		public void setColSpan(int colSpan) {
			this.colSpan = colSpan;
		}

		public String getGetMethodName() {
			return getMethodName;
		}

		public void setGetMethodName(String getMethodName) {
			this.getMethodName = getMethodName;
		}

	}
}


package com.poi.bean;

import com.poi.annotation.ExcelHeaderTitle;

public class TestBean extends TestBeanBase{
	
	@ExcelHeaderTitle(name="姓名", index=0, export=true)
	private String name;
	
	@ExcelHeaderTitle(name="性别", index=1, export=true)
	private String sex;
	
	@ExcelHeaderTitle(name="年龄", index=2, export=true)
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
}


package com.poi.bean;

import com.poi.annotation.ExcelHeaderTitle;

public class TestBeanBase {

	@ExcelHeaderTitle(name="标题测试", index=0, colSpan=3, export=true)
	private String title;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
	
}

G-ben 2014-03-06
  • 打赏
  • 举报
回复
楼主是在说借助反射 不依靠对象 访问none static member? java.lang.reflect 主要是无视访问修饰符的吧
java_liyi 2014-03-06
  • 打赏
  • 举报
回复
还是没看懂lz要做什么,是要将类里面的字段 getXXX方法呢 存到excel里面呢 还是要反射获取对象属性的值呢

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


public class A {
	
	
	private String id;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public A(String s){
		this.id = s;
	}
	
	
	public static void main(String[] args) {
		//反射获取方法
		Method[] ms = A.class.getDeclaredMethods();//
		for(Method m:ms){
			System.out.println(m.getName());
		}
		//反射获取属性
		Field[] fs = A.class.getDeclaredFields();
		for(Field f : fs){
			System.out.println(f.getName());
		}
		//反射获取构造函数
		Constructor[] cs = A.class.getConstructors();
		for(Constructor c : cs){
			System.out.println(c.getName());
		}
		
		//先初始化
		List<A> l = init();
		//反射获取属性的值
		for(A a : l){
			for(Field f : a.getClass().getDeclaredFields()){
				try {
					System.out.println(f.getName()+":"+f.get(a));//可以看做在此写入Excel
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
	}
	
	public static List<A> init(){
		List<A> l = new ArrayList<A>();
		for(int i = 0;i<100;i++){
			l.add(new A(i+""));
		}
		return l;
	}
}

这种?
shaguaanfanga 2014-03-05
  • 打赏
  • 举报
回复
public class Test {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
List<Model> list = new ArrayList<Model>();
for (int i = 0; i < 10; i++) {
list.add(new Model("model"+i));
}

Method[] methods = Model.class.getMethods();
for (Model model : list) {
for (Method method : methods) {
if(method.getName().equalsIgnoreCase("getName")){
System.out.println(method.invoke(model));
}
}
}
}

}
class Model{
private String name;

public Model(){
}
public Model(String name){
this.name = name;
}


public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

希望能帮到你
秋亦晚风 2014-03-05
  • 打赏
  • 举报
回复
解析名字只需一次就可以,而遍历list中的model就是invoke方法的obj参数,如果是常规的话,只需要遍历Field就可以了,可以得到指定对象的所有字段名和字段值。
kanorl 2014-02-22
  • 打赏
  • 举报
回复
遍历得到的model不就是method.invoke()的obj参数吗
平菇虾饺 2014-02-22
  • 打赏
  • 举报
回复
引用 2 楼 dring321 的回复:
[quote=引用 楼主 qyp199312 的回复:] 这两天无聊,想做一个打包Excel的小插件。 思路是这样的: 一、给出一个List<Model>, 二、遍历list逐个得到model。 三、通过反射获取model中变量名、public的getXXX方法。 四、写入Excel。 但是这儿出了一个很大的问题: 反射时得到的mothod.invoke(Object)方法Object必须实例化,也就是说其中肯定不可能有数据! 我就不明白怎么整了,问了一些人表示这个不可能。 我的理解大概是这样的、 能得到Class的各种信息相当于类对象在内存里面的位置已经显式的存在了。 List中的每个Model里面的数据应该也是能提取得到的,但是我就是不知道怎么整。
你的想法是对的。不过java没有提供这样的API吧。 帮顶![/quote] 昨晚想了一晚上,应该是没有的。不然这样的话内存里的数据对开发者将是可见的了,显然不安全了
代码间的舞者 2014-02-21
  • 打赏
  • 举报
回复
引用 楼主 qyp199312 的回复:
这两天无聊,想做一个打包Excel的小插件。 思路是这样的: 一、给出一个List<Model>, 二、遍历list逐个得到model。 三、通过反射获取model中变量名、public的getXXX方法。 四、写入Excel。 但是这儿出了一个很大的问题: 反射时得到的mothod.invoke(Object)方法Object必须实例化,也就是说其中肯定不可能有数据! 我就不明白怎么整了,问了一些人表示这个不可能。 我的理解大概是这样的、 能得到Class的各种信息相当于类对象在内存里面的位置已经显式的存在了。 List中的每个Model里面的数据应该也是能提取得到的,但是我就是不知道怎么整。
你的想法是对的。不过java没有提供这样的API吧。 帮顶!
平菇虾饺 2014-02-21
  • 打赏
  • 举报
回复
我想得到未知类的所有未知方法的返回值。 比如List<Model> Model: private String name; public String getName(){return name}

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧