Java实体类属性动态替换

2018-01-24 10:44:34来源:oschina作者:chencang001人点击

分享

public class JavaUtil {


public static String replaceFieldVal(Object t,String temlateStr){
if (null == t || null == temlateStr || temlateStr == ""){
return "";
}

String fieldName,fieldVal;
Field[] fields = t.getClass().getDeclaredFields();
for (Field field : fields){
field.setAccessible( true );
try {
fieldName = field.getName();
fieldVal = null == field.get(t) ? "" : field.get(t) + "";
if (temlateStr.contains(fieldName)){
String nameStr = "${" + fieldName + "}";
temlateStr = temlateStr.replace(nameStr, fieldVal);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}

return temlateStr;
}

}

微信扫一扫

第七城市微信公众平台