需求:有一個vo類,該類繼承了一個實體類,獲取到vo對象后,需要將其中的null值轉(zhuǎn)為空字符串;
思路:傳入?yún)?shù),用Object接收,利用反射獲取到該對象的所有字段,并判斷置空;
由于一開始沒有考慮到父類的字段獲取,導(dǎo)致時不時出現(xiàn)錯誤,因此這里簡單記錄一下。文章來源地址http://www.zghlxwxcb.cn/news/detail-733052.html
// 無需返回object,set后對象內(nèi)的值就已經(jīng)修改了
public static void setNullToEmpty(Object object){
Class<?> clazz = object.getClass();
Field[] fields = getAllFields(clazz);
for (Field field : fields) {
// 這里只處理類型為string的
if (field.getType().equals(String.class)) {
// get和set前都需要賦予訪問權(quán)限
field.setAccessible(true);
if (field.get(object) == null) {
DataUtil.setValue(object, field);
}
}
}
}
/**
* 設(shè)置新值
*
*
*/
public static void setValue(Object object, Field field) {
try{
Class<?> clazz = object.getClass();
field.setAccessible(true);
// 當(dāng)前對象是否屬于子類
if (field.getDeclaringClass() == clazz) {
field.set(object, "newValue");
} else {
Field parentField = clazz.getSuperclass().getDeclaredField(field.getName());
parentField.setAccessible(true);
parentField.set(object, "newValue");
}
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 獲取當(dāng)前類及其父類的所有字段信息
* @param clazz
* @return
*/
public static Field[] getAllFields(Class<?> clazz) {
Field[] allFields = clazz.getDeclaredFields(); // 獲取當(dāng)前類的所有字段
Class<?> superClass = clazz.getSuperclass();
// 若存在父類 則獲取父類信息
if (superClass != null) {
allFields = concatenate(getAllFields(superClass), allFields);
}
return allFields;
}
/**
* 合并子類 + 父類
* @param parent
* @param child
* @return
*/
public static Field[] concatenate(Field[] parent, Field[] child) {
int parentLen = parent.length;
int childLen = child.length;
Field[] c= new Field[parentLen+childLen];
System.arraycopy(parent, 0, c, 0, parentLen);
System.arraycopy(child, 0, c, parentLen, childLen);
return c;
}
文章來源:http://www.zghlxwxcb.cn/news/detail-733052.html
到了這里,關(guān)于反射——子父類字段獲取的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!