我有一个带有绑定(bind)类型和两个实现的通用接口(interface):
public interface IShapeConverter<T extends IShape> {
String convert(T shape);
}
public class SquareConverter implements IShapeConverter<Square> {
public String convert(final Square square) {
...
}
}
public class CircleConverter implements IShapeConverter<Circle> {
public String convert(final Circle circle) {
...
}
}
现在我想知道基于 IShape 类型获取实例的最佳方法是什么。我正在考虑在接口(interface)中使用静态方法,如下所示:
static IShapeConverter getInstance(final IShape shape) {
if (shape instanceof Circle) {
return new CircleConverter();
}
return new SquareConverter();
}
但我真的不想显式检查类型。当我调用转换时,这也会发出未经检查的警告:
void someFunction(final IShape shape) {
final IShapeConverter converter = IShapeConverter.getInstance(shape);
final String = converter.convert(shape); // Unchecked warning
...
}
必须有更好的方法来做到这一点..
编辑:添加完整的未经检查的警告
未经检查地调用“convert(T)”作为原始类型“my.package.IShapeConverter”的成员
最佳答案
您需要在方法中引入一些更通用的类型参数,但不幸的是,您能做的最好的事情就是将未经检查的警告移到其他地方:
static <T extends IShape> IShapeConverter<T> getInstance(final T shape) {
if (shape instanceof Circle) {
return (IShapeConverter<T>) new CircleConverter(); // Unchecked warning
}
return (IShapeConverter<T>) new SquareConverter(); // Unchecked warning
}
<T extends IShape> void someFunction(final T shape) {
final IShapeConverter<T> converter = IShapeConverter.getInstance(shape);
final String result = converter.convert(shape);
}
关于Java 泛型绑定(bind)类型和类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59213950/