StringConverter.java
private static class StringConverter<T> {
private static final List<StringConverter<?>> converters = Arrays.asList(
new StringConverter<>(String.class, String::toString),
new StringConverter<>(BigDecimal.class, BigDecimal::toPlainString),
new StringConverter<>(Date.class, Date::toString)
);
private final Class<T> clazz;
private final Function<T, String> converter;
static String convert(final Object object) {
if(object == null){
return null;
}
return converters.stream().filter(c -> c.isApplicable(object)).map(c -> c.doConvert(object)).findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unexpected class:" + object.getClass().getName()));
}
private StringConverter(final Class<T> clazz, final Function<T, String> converter) {
this.clazz = clazz;
this.converter = converter;
}
private boolean isApplicable(final Object object) {
return clazz.isInstance(object);
}
private String doConvert(final Object object) {
return converter.apply(clazz.cast(object));
}
}
I wrote it because I needed it, but I forgot what kind of situation it was because there was too much space.
String hoge = StringConverter<The class you want to convert(Please define it in converters)>.convert(obj);
After that, I didn't have a chance to use the generic type, so I wanted to use it.
I'm sorry if I made a lot of mistakes.
Recommended Posts