package com.myfutech.employee.service.provider.util;
import com.myfutech.employee.service.api.vo.request.employee.EmployeeModifyVO;
import com.myfutech.employee.service.provider.model.Employee;
import com.myfutech.employee.service.provider.util.vo.IFieldResult;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import java.lang.reflect.Field;
import java.util.Date;
/**
* Created by Liuxd on 2019/7/31.
*/
public class IBeanUtils {
public static IFieldResult containFieldName(Object obj, String filedName, String filedValue) throws Exception {
if (StringUtils.isBlank(filedName)) {
return new IFieldResult(false);
}
boolean flag = false;
String type = "";
Object value = null;
for (Field f : obj.getClass().getDeclaredFields()) {
f.setAccessible(true);
if (filedName.equals(f.getName())) {
flag = true;
type = f.getType().toString();
if (type.contains("Date")) {
if(!filedValue.contains(":")){
filedValue = filedValue + " 00:00:00";
}
value = DateUtils.parseDate(filedValue, "yyyy-MM-dd HH:mm:ss");
} else {
value = filedValue;
}
break;
}
}
return new IFieldResult(flag, type, value);
}
public static String getFieldValueByFieldName(String fieldName, Object object) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
//设置对象的访问权限,保证对private的属性的访问
field.setAccessible(true);
Object hisValue = field.get(object);
if (null == hisValue) {
return "";
}
String value = "";
String type = field.getType().toString();
if (type.contains("Date")) {
value = DateFormatUtils.format((Date) hisValue, "yyyy-MM-dd HH:mm:ss");
} else {
value = hisValue.toString();
}
return value;
} catch (Exception e) {
return "";
}
}
public static String getFieldTypeByFieldName(String fieldName, Object object) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
//设置对象的访问权限,保证对private的属性的访问
field.setAccessible(true);
String type = field.getType().toString();
return type;
} catch (Exception e) {
return "";
}
}
public static String getFieldAnnotation(String fieldName, Object object) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
//设置对象的访问权限,保证对private的属性的访问
field.setAccessible(true);
ApiModelProperty property = field.getAnnotation(ApiModelProperty.class);
if (null == property) {
return "";
}
return property.value();
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) throws Exception {
EmployeeModifyVO vo = new EmployeeModifyVO();
IFieldResult result = IBeanUtils.containFieldName(vo, "employeeName", "99999");
System.out.println(result.toString());
vo.setEmployeeName("Jack");
Object v = getFieldValueByFieldName("employeeName", vo);
System.out.println(v);
Employee employee = new Employee();
employee.setCreateTime(new Date());
String v2 = getFieldValueByFieldName("createTime", employee);
System.out.println(v2);
}
}