反射的基本应用

   应用1:示例化对象、获取对象属性及属性类型

List<Object> getGetUserDatas=parseResult(userStr, GetUserData.class,false);  
  
public static List<Object> parseResult(String xml,Class<?> t,boolean isOrder){  
    return parseResult(xml,t,new PageBean<Object>(),isOrder);  
}  
  
public static List<Object> parseResult(String xml,Class<?> t,PageBean<Object> pageBean,boolean isOrder) {  
	......  
	//根据传过来的Class反射生成类  
	Object obj=t.newInstance();  
	  
	//得到类的名称  
	String className = t.getSimpleName();  
  
	//得到类中所有的属性  
	Field[] fields=t.getDeclaredFields();  
	String sname = fields[1].getName(); // 获取属性的名字  
	String sname2 = fields[2].getName(); // 获取属性的名字  
		  
	//得到类的属性字段申明,返回一个 Field 对象  
	Field field=t.getDeclaredField(attr);  
  
	//Field.getType(),返回一个 Class 对象,它标识了此 Field 对象所表示字段的声明类型。  
	//Class.getSimpleName(),返回一个 Field 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明字段,如:int、double、String......  
	String fieldTypeName=field.getType().getSimpleName();  
	  
	if(fieldTypeName.equals("int")||fieldTypeName.equalsIgnoreCase("Integer")){  
		field.set(obj, Integer.parseInt(value));  
	}else if (fieldTypeName.equalsIgnoreCase("double")) {  
		field.set(obj, Double.parseDouble(value));  
	}  
	......  
}

说明:
    Field对象:
    getType()
        返回一个 Class 对象,它标识了此 Field 对象所表示字段的声明类型。
      
Class对象:
    newInstance()
          创建此 Class 对象所表示的类的一个新实例。
        
    String getSimpleName()
          返回源代码中给出的底层类的简称。
        
    getDeclaredField(String name)
          返回一个 Field 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明字段。


    getDeclaredFields()
          返回 Field 对象的一个数组,这些对象反映此 Class 对象所表示的类或接口所声明的所有字段。

应用2:Excel文件导出公共方法(根据穿过来的类设置导出内容)

/**
 * @param list 查询的列表集合(转范型之后的集合)
 * @param fileName 资源文件名
 * @param headArray  头部数组
 * @param widthArray  设置excel每列的宽度
 * @param cols 显示多少列减1
 * @param c 反射的类(通过它可以访问类中的属性以及方法)
 * @return
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
public static String export(List list,String fileName,String[] headArray,int[] widthArray,int cols,Class<?> c)throws Exception{
	try{ 
		/*********创建excel阶段*********/ 
		//创建Excel的工作书册 Workbook,对应到一个excel文档  
		HSSFWorkbook wb = new HSSFWorkbook();  
		//创建Excel的工作sheet,对应到一个excel文档的tab  
		HSSFSheet sheet = wb.createSheet("sheet1");
		
		
		//设置excel每列宽度  
		for (int i = 0; i < widthArray.length; i++) {
			sheet.setColumnWidth(i,widthArray[i]);
		}
		
		//创建execl第一行数句(标题)
		String name=fileName+"-";
		HSSFRow row = ExcelExportUtil.createTopFile(wb,sheet,cols,name + DateUtil.today() );
			//创建第二行数据
			row = ExcelExportUtil.createTwoRow(wb,sheet,row,headArray,1);
		  
			/***********开始写第二行已下的数据************/
			int num = 2;	//表示第几行
			HSSFCell cell;	//单元格
			//样式
			HSSFCellStyle styleTwo = wb.createCellStyle();  
			styleTwo.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			
			//得到类中所有的属性
			Field[] fields=c.getDeclaredFields();
			
			for (Object object : list) {
				row = sheet.createRow(num);	
				int lieNum = 0;		//列号
				for (int i = 0; i < fields.length; i++) {
					//获取属性的名字
					String sname = fields[i].getName(); 
					//将属性的首字符大写,方便构造get,set方法
					sname = sname.substring(0, 1).toUpperCase() + sname.substring(1); 
					System.out.println(fields[i].getGenericType()+":============================");
					if(fields[i].getGenericType().toString().equals("class java.lang.String")){
						//object.getClass(),返回此 Object 的运行时类
						//getMethod("get" +sname) 返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。
						Method m = (Method) object.getClass().getMethod("get" +sname);  
						
						//对带有指定参数的指定对象调用由此 Method 对象表示的底层方法,获取值
						String val = (String) m.invoke(object);
						if (val != null) {  
							System.out.println("String type:" + val);  
							cell = row.createCell(lieNum++);
							cell.setCellStyle(styleTwo);
							cell.setCellValue(val);
						}  
					}
					
					//如果类型是Integer  
					//fields[i].getGenericType().toString() 获取属性的类型
					if (fields[i].getGenericType().toString().equals("class java.lang.Integer")) {  
						Method m = (Method) object.getClass().getMethod("get" +sname);  
						Integer val = (Integer) m.invoke(object);  
						if (val != null) {  
							System.out.println("Integer type:" + val);  
							cell = row.createCell(lieNum++);
							cell.setCellStyle(styleTwo);
							cell.setCellValue(val+"");
						}  
					}  
					
					// 如果类型是Double  
					if (fields[i].getGenericType().toString().equals("class java.lang.Double")) {  
						Method m = (Method) object.getClass().getMethod("get" + sname);  
						Double val = (Double) m.invoke(object);  
						if (val != null) {  
							System.out.println("Double type:" + val);  
							cell = row.createCell(lieNum++);
							cell.setCellStyle(styleTwo);
							cell.setCellValue(val+"");
						}  
					}  
					// 如果类型是Boolean 是封装类  
					if (fields[i].getGenericType().toString().equals("class java.lang.Boolean")) {  
						Method m = (Method) object.getClass().getMethod(sname);  
						Boolean val = (Boolean) m.invoke(object);  
						if (val != null) {  
							System.out.println("Boolean type:" + val);  
							cell = row.createCell(lieNum++);
							cell.setCellStyle(styleTwo);
							cell.setCellValue(val+"");
						}  
					}  
					// 如果类型是boolean 基本数据类型不一样 这里有点说名如果定义名是 isXXX的 那就全都是isXXX的  
					// 反射找不到getter的具体名  
					if (fields[i].getGenericType().toString().equals("boolean")) {  
						Method m = (Method) object.getClass().getMethod(sname);  
						Boolean val = (Boolean) m.invoke(object);  
						if (val != null) {  
							System.out.println("boolean type:" + val);  
							cell = row.createCell(lieNum++);
							cell.setCellStyle(styleTwo);
							cell.setCellValue(val+"");
						}  
					}  
					// 如果类型是Short  
					if (fields[i].getGenericType().toString().equals("class java.lang.Short")) {  
						Method m = (Method) object.getClass().getMethod("get" + sname);  
						Short val = (Short) m.invoke(object);  
						if (val != null) {  
							System.out.println("Short type:" + val);  
							cell = row.createCell(lieNum++);
							cell.setCellStyle(styleTwo);
							cell.setCellValue(val+"");
						}  
					}  
				}
				num++;
			}
			//导出文件存放路劲
			String patch= Thread.currentThread().getContextClassLoader().getResource("/").toString();
			patch = patch.substring(6,patch.lastIndexOf("WEB-INF/"));
			patch = patch + "produceFile/";
			//文件名
			String exportfileName = name + DateUtil.today() + ".xls";
			FileOutputStream os = new FileOutputStream(patch + exportfileName);
			wb.write(os);  
			os.close();
			return exportfileName;
	}catch(Exception e){
		e.printStackTrace();
		System.out.println("存储失败");
		return "false";
	}
}

猜你喜欢

转载自x125858805.iteye.com/blog/2200351