最近在写一个接口,参数用一个对象接收。需要判断对象里的属性必填项
一、获得 所有的属性名
/**
*get the object property, Gets an array of strings
*
* @param object
* @return String[]
*/
public static String[] getFiledName(Object object) {
List<String> list = Arrays.asList(mustFiled);
try {
Field[] fields = object.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
fieldNames[i] = fields[i].getName();
}
return fieldNames;
} catch (SecurityException e) {
e.printStackTrace();
}
return null;
}
二、获得属性中的值
/**
* Gets the value of the attribute value from the attribute name
*
* @param fieldName
* @param object
*/
public static Object getFieldValueByName(String fieldName, Object object) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = object.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(object, new Object[] {});
if (value == null) {
LOG.error("fieldValue is null: " + fieldName);
}
return value;
} catch (Exception e) {
LOG.error("fieldName is not exit: " + fieldName);
return null;
}
}
三、判断属性是否为null
private static Logger LOG = LoggerFactory.getLogger(CheckAttributeUtil.class);
private static String[] mustFiled = {"filed", ...};
public static String checkAttribute(Object object) {
StringBuilder returnBuilder = new StringBuilder("SUCCESS");
List<String> list = Arrays.asList(mustFiled);
String[] fieldNames = getFiledName(object);
for (String fieldName : fieldNames) {
if (list.contains(fieldName)) {
Object value = getFieldValueByName(fieldName, object);
if (value == null) {
LOG.error("fieldValue is null: " + fieldName);
System.out.println("fieldValue is null: " + fieldName);
returnBuilder.append("fieldValue is null: " + fieldName);
}
}
}
return returnBuilder.toString();
}