Converting one type to another

I need to improve this code:

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);
}

So, I decided to implement Transformer-like, which converts the type Xto another Y.

I created this interface

public interface Converter<S, D> {
  D convert(final S source);

  Class<D> getDestinationClass();
  Class<S> getSourceClass();
}

so when I need to implement the conversion, I implement this interface

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;
  }
}

(example String -> Integer)

Now for type conversion, I have another class Convertersthat is contained inside the table (a Guava table with two keys), where all the converters are stored.

private final static ImmutableTable<Class<?>, Class<?>, Converter<?, ?>> converters;

And has a method 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)));
}

Error

incompatible types: S cannot be converted to capture#1 of ?

at source.cast(value)

because I store them on the map using ?, so I am stuck. I do not know how I can fix this. I got the feeling that this is not possible, but I am publishing to find out if I am not mistaken.

I read this from Spring, but it is different.

+4
1

, , :

@SuppressWarnings("unchecked")
public <S, D> D convert(final Class<S> source, final Class<D> destination, final S value) {
    final Converter<S, D> converter = (Converter) converters.get(source, destination);

    return destination.cast(converter.convert(source.cast(value)));
}

. , 3 , Table, .

+3

Source: https://habr.com/ru/post/1598959/


All Articles