Christopher Klewes
Christopher Klewes

Reputation: 11435

How to fix this generic problem within the repository pattern?

I have a type converter which converts a string into an object and vice versa, the type converter takes the local into account. To implement easily several type converters, e.g. for BigDecimal, Point, and so on I decided to make this interface generic.

public interface TypeConverter<T extends Object>
{ 
    convertToString(Locale locale, T object);
}

This is great to implement as you can be sure you only get the desired T and don't have to cast or something else.

convertToString(Locale locale, BigDecimal bigDecimal) { ... }

To retrieve the correct converter, I build up a type converter repository where you can access a specific type converter

 typeConverterRepository.getTypeConverter(sourceValue.getType())

The type converter repository than gives us the correct type converter.

Now we want to call this converter:

TypeConverter typeConverter = typeConverterRepository.get( ....)
typeConverter.convertToString(context.getLocale(), sourceValue.getValue());

This leads into an eclipse warning:

The method convertToString(Locale, capture#2-of ?) in the type TypeConverter<capture#2-of ?> is not applicable for the arguments (Locale, Object)

How can this be fixed without using the @SupressWarning annotation? Thank you!

Upvotes: 2

Views: 229

Answers (1)

jontro
jontro

Reputation: 10628

I think the problem lies within your typeConverterRepository pattern.

Do a typeconverter that looks like the following

public class TypeConverterRepository {
    public <T> void registerTypeConverter(Class <T> type, TypeConverter<T> typeConverter);
    public <T> TypeConverter<T> getTypeConverter(Class <T> type);
}

Then you can safley do a

TypeConverter<MyClass> typeConverter = typeConverterRepository.getTypeConverter(MyClass.class);

Upvotes: 2

Related Questions