-
Notifications
You must be signed in to change notification settings - Fork 2
TypeAdapters
Type adapters are a well known concept from Fit. They are used to parse strings into objects, to compare those, and to transform those back into strings. However, there is a problem with Fit: it is really hard to use types which Fit doesn't know. How to handle oracles Date object? Another drawback on the default implementation is, that some objects needs some help to determine, if they are equal (think about comparing two StringBuilders
). If you only need to parse strings, because equals()
and toString()
work fine, take a look at Parsers.
FitGoodies adds support to register new type adapters. These adapters replace the original ones.
Here is one example which is used inside of FitGoodies:
package de.cologneintelligence.fitgoodies.adapters;
import fit.TypeAdapter;
public class StringBuilderTypeAdapter extends AbstractTypeAdapter<StringBuilder> {
public StringBuilderTypeAdapter(final TypeAdapter ta, final String parameter) {
super(ta, parameter);
}
@Override
public final Class<StringBuilder> getType() {
return StringBuilder.class;
}
@Override
public final boolean equals(final Object a, final Object b) {
if (a == null) {
return b == null;
}
if (b == null) {
return false;
}
return a.toString().trim().equals(b.toString().trim());
}
@Override
public final String toString(final Object o) {
if (o == null) {
return "null";
}
return o.toString();
}
@Override
public Object parse(final String s) throws Exception {
return new StringBuilder(s);
}
}
The type adapter is registered with:
de.cologneintelligence.fitgoodies.adapters.TypeAdapterHelper.instance().register(StringBuilderTypeAdapter.class);
Type adapters can also be registered via HTML using an appropriate SetupFixture. As soon as a type adapter is registered, it is automatically used if FitGoodies must convert a string into a corresponding object.