在我的 Java 项目中,我有一个使用泛型类型的抽象类。我的类由一些具体的子类扩展和实现。我的源代码是这样的:
class Metrics<T extends Dataset>
{
public float evaluate(T dataset, Entity x, Entity y);
}
class MetricsType1 extends Metrics<DatasetType1>
{
public float evaluate(DatasetType1 dataset, Entity x, Entity y);
}
class MetricsType2 extends Metrics<DatasetType2>
{
public float evaluate(DatasetType2 dataset, Entity x, Entity y);
}
在我的主应用程序中,我以这种方式使用我的类:
Metrics<DatasetType1> metrics1 = new MetricsType1();
Metrics<DatasetType2> metrics2 = new MetricsType2();
我想使用相同的引用“metrics”,而不是使用两个不同的引用“metrics1”和“metrics”,以便我可以使用 MetricsType1 或 MetricsType2 类实例化我的“metrics”引用,而无需编写两个单独的引用引用文献。
我特别想写这样的东西:
Metrics metrics = null;
metrics = new MetricsType1();
// ...
metrics = new MetricsType2();
显然,Java 解释器向我发出警告,告诉我应该为 Metrics 类的泛型使用参数。
我该如何处理这个问题?
谢谢!
最佳答案
使用通配符:
Metrics<?> metrics;
或者,如果您想更具体的话:
Metrics<? extends Dataset> metrics;
在这种特殊情况下,这些都是同义词,因为 Metrics
的定义使得 T 扩展了 Dataset
。
但是请注意,使用此定义时,evaluate
方法无法直接调用。您必须将对象转换为具体的子类才能完成此操作。
关于java - 使用泛型创建类的基类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19661756/