我需要改进这段代码:
错误信息是:
final String valueString = value.toString();
if (Path.class.isAssignableFrom(destinationType)) {
fixedValues.put(key, Paths.get(valueString));
} /* ... as above, for other types ... */ {
} else {
fixedValues.put(key, valueString);
}
因此,我决定实现一个类似Transformer的功能,将类型X
转换为另一种类型Y
。
我创建了这个接口
public interface Converter<S, D> {
D convert(final S source);
Class<D> getDestinationClass();
Class<S> getSourceClass();
}
当我需要实现转换时,我会实现这个接口。
public class StringToIntegerConverter implements Converter<String, Integer> {
@Override
public Integer convert(final String source) {
return Integer.parseInt(source);
}
@Override
public Class<Integer> getDestinationClass() {
return Integer.class;
}
@Override
public Class<String> getSourceClass() {
return String.class;
}
}
(String 转 Integer 的示例)
现在,为了转换类型,我有另一个名为 Converters
的类,其中包含一个表格(使用两个键的 Guava 表格),其中存储了所有转换器。
private final static ImmutableTable<Class<?>, Class<?>, Converter<?, ?>> converters;
并且有一个名为convert
的方法
public <S, D> D convert(final Class<S> source, final Class<D> destination, final S value) {
return destination.cast(converters.get(source, destination).convert(source.cast(value)));
}
错误信息是:
incompatible types: S cannot be converted to capture#1 of ?
在 source.cast(value)
处
因为我使用 ?
将它们存储在映射中,所以我陷入了困境。我不知道如何解决这个问题。我有一种感觉,这是不可能的,但我发帖想看看我是否错了。
我阅读了 Spring 的 这篇文章,但那是另一种方式。