/** * Gets the name of all fields (public, private, protected, default) of the given instance or class. This includes as well all * fields (public, private, protected, default) of all its super classes. * * @param instanceOrClass the instance or class to get the fields of * @return the collection of field names of the given instance or class * * @see PrivilegedAccessor#getFieldNames(Object) */ public static Collection<String> getFieldNames(final Object instanceOrClass) { return PrivilegedAccessor.getFieldNames(instanceOrClass); }
/** * Gets the name of all fields (public, private, protected, default) of the given instance or class. This includes as well all * fields (public, private, protected, default) of all its super classes. * * @param instanceOrClass the instance or class to get the fields of * @return the collection of field names of the given instance or class */ public static Collection<String> getFieldNames(final Object instanceOrClass) { if (instanceOrClass == null) return Collections.EMPTY_LIST; Class<?> clazz = getClass(instanceOrClass); Field[] fields = clazz.getDeclaredFields(); Collection<String> fieldNames = new ArrayList<String>(fields.length); for (Field field : fields) { fieldNames.add(field.getName()); } fieldNames.addAll(getFieldNames(clazz.getSuperclass())); return fieldNames; }
/** * Returns a string representation of the given object. The string has the following format: "<classname> {<attributes and values>}" * whereas <attributes and values> is a comma separated list with <attributeName>=<attributeValue> <atributes and values> includes * all attributes of the objects class followed by the attributes of its superclass (if any) and so on. * * @param instanceOrClass the object or class to get a string representation of * @return a string representation of the given object */ public static String toString(final Object instanceOrClass) { Collection<String> fields = getFieldNames(instanceOrClass); if (fields.isEmpty()) return getClass(instanceOrClass).getName(); StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(getClass(instanceOrClass).getName() + " {"); for (String fieldName : fields) { try { stringBuffer.append(fieldName + "=" + getValue(instanceOrClass, fieldName) + ", "); } catch (NoSuchFieldException e) { assert false : "It should always be possible to get a field that was just here"; } } stringBuffer.replace(stringBuffer.lastIndexOf(", "), stringBuffer.length(), "}"); return stringBuffer.toString(); }