有条件地改变对象类Java

ely*_*33t 0 java class

所以我有一段代码看起来像这样:

Metrics metrics = null;

try {
    metrics = metricsService.getCurrentMetrics();
} catch (SQLException e) {
    e.printStackTrace();
}

//Do some stuff with the metrics
Run Code Online (Sandbox Code Playgroud)

我最近实现了一种单独的机制,作为在单独的类下跟踪API指标的一种方式,巧妙地称为APIMetrics.

因此,通过此更改,代码看起来像这样:

Metrics metrics = null;
APIMetrics apiMetrics = null;

try {
    if(user.isAPI())
        apiMetrics = metricsService.getCurrentAPIMetrics();

    else
        metrics = metricsService.getCurrentMetrics();
} catch (SQLException e) {
    e.printStackTrace();
}

//Do some stuff with the metrics
Run Code Online (Sandbox Code Playgroud)

问题在于下面的代码"使用指标做一些事情"都是根据使用指标对象编写的.有没有办法我可以设置它,以便"metrics"对象不仅指代Metrics类型的对象,而且我们想要使用的对象是什么?

因此,例如,如果我们有非API用户,我们希望指标的类型为Metrics,结果为metricsService.getCurrentMetrics().但是,如果我们有一个API用户,我们希望指标的类型为APIMetrics,结果是metricsService.getCurrentAPIMetrics().

有什么好办法可以解决这个问题吗?Metrics和APIMetrics类共享所有方法.我知道可能有一种方法可以使用继承或多态来做到这一点,但我无法弄明白该做什么.谢谢!

Lui*_*oza 5

制作两个类MetricsAPIMetrics实现相同的接口.然后,声明一个类型为此接口的单个​​变量,相应地初始化它并通过代码使用它.