import java.lang.reflect.Method;
public class ReflectUtil {
//动态设置字段
public static void setValue(Object dto, String name, Object value) {
try {
Method[] m = dto.getClass().getMethods();
for (int i = 0; i < m.length; i++) {
if (("set" + name).toLowerCase().equals(m[i].getName().toLowerCase())) {
m[i].invoke(dto, value);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//动态获取字段值
public static String getValue(Object dto, String name) {
try {
Method[] m = dto.getClass().getMethods();
for (int i = 0; i < m.length; i++) {
if (("get" + name).toLowerCase().equals(m[i].getName().toLowerCase())) {
return (String) m[i].invoke(dto);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}