@UtilityClass
public class ClassUtil {
public Object getGetMethod(Object obj, String name) throws Exception {
Method[] methods = obj.getClass().getMethods();
for (Method method : methods) {
if (("get" + name).equalsIgnoreCase(method.getName())) {
return method.invoke(obj);
}
}
return null;
}
public void setValue(Object obj, Class<?> clazz, String filedName, Class<?> typeClass, Object value) {
filedName = removeLine(filedName);
String methodName = "set" + filedName.substring(0, 1).toUpperCase() + filedName.substring(1);
try {
Method method = clazz.getDeclaredMethod(methodName, typeClass);
method.invoke(obj, getClassTypeValue(typeClass, value));
} catch (Exception ex) {
ex.printStackTrace();
}
}
private Object getClassTypeValue(Class<?> typeClass, Object value) {
if (typeClass == int.class || value instanceof Integer) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == short.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == byte.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == double.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == long.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == String.class) {
if (null == value) {
return "";
}
return value;
} else if (typeClass == boolean.class) {
if (null == value) {
return true;
}
return value;
} else if (typeClass == BigDecimal.class) {
if (null == value) {
return new BigDecimal(0);
}
return new BigDecimal(value + "");
} else {
return typeClass.cast(value);
}
}
public String removeLine(String str) {
if (null != str && str.contains("_")) {
int i = str.indexOf("_");
char ch = str.charAt(i + 1);
char newCh = (ch + "").substring(0, 1).toUpperCase().toCharArray()[0];
String newStr = str.replace(str.charAt(i + 1), newCh);
return newStr.replace("_", "");
}
return str;
}
}