I have a conception problem on my ConverterManager. ConverterManager is an object that convert a type to an other type. As you can see below, I got an error when I’m tyring to create “convert” function.
public class StringIntegerConverter implements Converter<String, Integer> {
@Override
public Integer convert(String from) {
//...
return Integer.valueOf(from);
}
}
public class ConverterManager {
private static Map<Key,Converter<?,?>> converterRegistry;
{
converterRegistry = new HashMap<Key, Converter<?,?>>();
converterRegistry.put(new Key(String.class, Integer.class), new StringIntegerConverter());
}
public <T> T convert(Object source, Class<T> toType)
{
//**ERROR HERE : cause "source" is an Object**
return converterRegistry.get(new Key(source.getClass(),toType)).convert(source);
}
}
- Is there a way to solve this problem ? (I don’t want to change my StringIntegerConverter to accepet converting from Object)
Thank you for reading, I hope someone will help me 😉
Basically you’ll have to perform an unsafe conversion – at execution time, the JVM can’t check that you’ve really got a
Converter<String, Integer>. That leaves the problem of persuading it to accept the input. You can do that via a “proxying” converter class which implementsConverter<Object, ?>:This is messy and it feels like there should be a better way, but it’s all I’ve got at the moment…