Freitag, 15. August 2014

Generic toString() for Entities in JAVA

@Override
public String toString() {
    Class clazz = getClass();
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(getClass().getSimpleName());
    stringBuilder.append("@" + Integer.toHexString(System.identityHashCode(this)));

    stringBuilder.append("[");

    List<field> printableFields = new ArrayList<field>();

    while (clazz != null) {
        Field[] fields = clazz.getDeclaredFields();
    
        for (Field field : fields) {
            if (byte[].class.isAssignableFrom(field.getType()) || Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()) || field.isAnnotationPresent(Transient.class)) {
                continue;
            }
            printableFields.add(field);
        }
        clazz = clazz.getSuperclass();
    }

    for (int i = 0; i &lt; printableFields.size(); i++) {
        Field field = printableFields.get(i);
        field.setAccessible(true);
        Object fieldValue = null;

        try {
            fieldValue = field.get(this);
        } catch (IllegalAccessException e) {
            continue;
        }

        stringBuilder.append(field.getName() + "=" + fieldValue);
        if (i &lt; (printableFields.size() - 1)) {
                stringBuilder.append(", ");
        }
    }

    stringBuilder.append("]");
    return stringBuilder.toString();
}

0 Kommentare:

Kommentar veröffentlichen