java - 如何在存储库模式中解决这个一般问题?

标签 java eclipse generics

我有一个类型转换器,可以将字符串转换为对象,反之亦然,类型转换器考虑了本地。轻松实现多种类型转换器,例如对于 BigDecimal , Point , 等等 我决定使这个接口(interface)通用。

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

这非常适合实现,因为您可以确保只获得所需的 T 而不必强制转换或执行其他操作。

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

为了检索正确的转换器,我构建了一个类型转换器存储库,您可以在其中访问特定的类型转换器

 typeConverterRepository.getTypeConverter(sourceValue.getType())

类型转换器存储库为我们提供了正确的类型转换器。

现在我们要调用这个转换器:

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

这会导致 eclipse 警告:

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

如何在不使用 @SupressWarning 的情况下解决这个问题?注解?谢谢!

最佳答案

我认为问题在于您的 typeConverterRepository 模式。

做一个类似下面的类型转换器

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

然后你可以safley做一个

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

关于java - 如何在存储库模式中解决这个一般问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7567136/

相关文章:

java - 在 String 字段上指定关键字类型

java - 我应该如何声明和导出模块?

python - PIL库导入失败

c# - .Net 没有 Hashset<T, G> 吗?

c++ - 编译时类继承

c# - 泛型中的 <out T> 与 <T>

java - 从txt文件读取数据,创建对象,添加到集合

windows - 无法在 Eclipse 中运行 junit 测试

带有 OpenCv : UnsatisfiedLinkError under Eclipse if use spring-boot-devtools 的 Java Spring 启动应用程序

java - 在 JSP 中更新数据库