运用java反射为实体类取值赋值

运用java反射对实体类取值赋值

取值的方法为: 字段.get(实体类)

//举例
//field 为实体类user中的一个字段
  field.get(user);

赋值的方法为:字段.set(实体类)

 //举例
 //field 为实体类staff中的一个字段
  field.set(staff)

具体应用如下:

/**
*User 为传来的带值的实体类
*Staff 为要赋值的实体类
*@return
*/
public void getSetStaff(User user) {
	Staff staff= new Staff();
	// getDeclaredFields()
	//获取 此实体类中所有字段
	Field[] fieldUser = user.getClass().getDeclaredFields();   
	Field[] fieldStaff = staff.getClass().getDeclaredFields();
	//从user实体类中取值
	for (int i=0;i<fieldUser.length;i++){
	  //访问其中的私有变量权限
		fieldUser[i].setAccessible(true);
		//获取字段的名字
		String userName = fieldUser[i].getName();
		Object userGetVal = null;
		try {
		  //如果要获取的字段的值不是静态字段,则需要将此实体类中对象传进去
			userGetVal = fieldUser[i].get(user); 
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		if (userGetVal != null) {
		  //为staff实体类赋值
			for (int j = 0; j < fieldStaff.length; j++) {
				Field staffF = fieldStaff[j];
				//获取实体类中字段的名字
				String staffName = staffF.getName();
				if (userName.equals(staffName)){
				    //访问其中私有变量的权限
					staffF.setAccessible(true);
					//获取此字段的数据类型
					String type= staffF.getType().toString();
					if(type.endsWith("String")){
						try {
						   // 给属性设值
							staffF.set(staff,(String)userGetVal); 
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						}
					}else if(type.endsWith("int") || type.endsWith("Integer")) {
						try {
							 // 给属性设值
							staffF.set(staff,(int)userGetVal); 
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						}
					} else {
					//日期格式
						try {
							 // 给属性设值
							staffF.set(staff,(Date)userGetVal); 
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						}
				   }
				}
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39909133/article/details/83749076