欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

合并类里所有属性值

程序员文章站 2022-03-26 12:13:53
...
public String combineAllFields(String split) {
    final Field[] fields = this.getClass().getDeclaredFields();
    if (fields.length < 1) {
        return null;
}
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < fields.length; i++) {
        char[] cs = fields[i].getName().toCharArray();
cs[0] -= 32;
        try {
            Method method = this.getClass().getMethod("get" + String.valueOf(cs));
String fieldValue = (String) method.invoke(this, new Object[]{});
result.append(fieldValue).append(split);
} catch (Exception e) {
            e.printStackTrace();
}
    }
    return result.toString().endsWith(split) ? result.substring(0, result.length() - 1) : result.toString();
}