I have an idea for improved Java object type conversion (converting from
one Java object type to another), and I would like to solicit comments
from the community.
Currently, the project handles object type conversions in the
ObjectType.simpleTypeConvert(...) method, and there are small conversion
code snippets in other classes (UtilDateTime for example). Basically,
object type conversion is scattered all over the project. This can lead
to code inconsistency, or inconsistent conversion results.
I think it would be helpful to consolidate object type conversion into a
simple "framework" that can be easily extended to handle additional
conversions.
I came up with a simple interface:
public interface Converter<T, F> {
public T to(F obj);
}
where T is the object type to convert to, and F is the object type to
convert from.
A factory class is used to get a Converter instance:
public class ConverterFactory {
public static <T, F> Converter<T, F> getConverter(Class<T> toClass,
Class<F> fromClass) {}
}
To convert an object:
String str = "1234";
Converter<Long, String> converter = ConverterFactory
.getConverter(Long.class, String.class);
Long result = converter.to(str);
The framework would include converter implementations for all the
conversions currently being used. The ObjectType.simpleTypeConvert(...)
method's complicated if-else code would be replaced with the simpler
converter code.
Users can write their own converters and "register" them with the
converter framework.
What do you think?
-Adrian