Hi,
I have created a simple API to convert arbitrary objects into human-readable strings. Think of it as a generalized String.valueOf()
functionality.
The API achieves this by selecting an
public interface ObjectFormatter {
public String format(Object object);
public Class getObjectClass();
public boolean offer(Object object);
}
depending on the getClass()
method of the particular object, and then passing the object to the format()
method. Mapping is done through a simple lookup:
Class clazz = object.getClass();
ObjectFormatter formatter = this.formatters.get(clazz);
if(formatter != null)
return formatter;
However, this of course only works in cases where object class and key class are exactly the same, but the API must also be able to map key class derivatives (or implementations, if the key is an interface
) to the same formatter, otherwise I would end up mapping a Throwable
formatter to each possible exception class in my application.
Therefore, when the above lookup fails, my current solution is to walk through the whole map and ask each formatter if it is capable of formatting my object. Yet I'm not too happy with this, and I wonder if there might be a better way.
Well, the strict OOP way with simply overriding toString()
and forgetting about the formatter would work on my own classes but fails at 3rd-party libraries, especially when a particular toString()
implementation does not include the desired information about the object.