public class ClazUtil {
private static Logger logger = LoggerFactory.getLogger(ClazUtil.class);
public static String verifyDTO(Object o,String[] names) {
if(o == null){
String msg = "接口参数data不能为空!";
logger.error(msg);
return msg;
}
if(names == null || names.length == 0){
String msg = "名字不能为空!";
logger.error(msg);
return "";
}
StringBuffer error = new StringBuffer();
Object[] values = ClazUtil.getFiledValues(o);
String[] types = ClazUtil.getFiledTypes(o);
if(values.length != names.length) {
logger.error("名字和属性个数不匹配!");
return "";
}
for(int i = 0;i < values.length;i++){
Object value = values[i];
String type = types[i];
String name = names[i];
try {
Class<?> typeClaz = Class.forName(type);
if(typeClaz == String.class){
if(StringUtils.isEmpty(String.valueOf(value)) || value == null) error.append(name).append("为空!\n");
}else{
if(value == null) error.append(name).append("不能为空!\n");
}
} catch (ClassNotFoundException e) {
logger.error(e.getMessage());
continue;
}
}
return error.toString();
}
/**
* 获取对象的所有属性值,返回一个对象数组
*/
public static Object[] getFiledValues(Object o) {
Field[] fields = o.getClass().getDeclaredFields();
Object[] value = new Object[fields.length];
for (int i = 0; i < fields.length; i++) {
Object mValue = null;
try {
String filedName = fields[i].getName();
String firstLetter = filedName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + filedName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[] {});
mValue = method.invoke(o, new Object[] {});
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
value[i] = mValue;
}
return value;
}
/**
* <p>date: 2015年8月13日 上午10:06:03</p>
* <p>description: 获取对象的所有类型 </p>
* @author muzi131313
* @param
* @return
*/
public static String[] getFiledTypes(Object o){
Field[] fields = o.getClass().getDeclaredFields();
String[] fieldTypes = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
String type = fields[i].getType().toString();
if(type.contains("class ")) type = type.replaceAll("class ", "");
fieldTypes[i] = type;
}
return fieldTypes;
}
/**
* <p>date: 2015年6月24日 下午12:18:09</p>
* <p>description: 获取实例变量名称和@column注解中name </p>
* @author muzi131313
* @param 带有@Column注解的pojo的类
* @return Map<filedName,columnName>
*/
public static Map<String,String> getFiledNameAndColumnName(Class<?> claz) {
Field[] fields = claz.getDeclaredFields();
Map<String,String> map = new HashMap<String,String>();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String fieldName = field.getName();
Annotation[] as = field.getAnnotations();
for(Annotation a : as){
Class<?> type = a.annotationType();
if(type == javax.persistence.Column.class){
try {
javax.persistence.Column c = (javax.persistence.Column)a;
String columnName = c.name();
if(StringUtils.isEmpty(columnName)){
columnName = fieldName;
}
map.put(fieldName, columnName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return map;
}
public static void main(String[] args) {
}
}