使用类型边界调用接口中不存在的 class 中的方法

Calling a method in a class which is not there in interface, using type bounds

我有以下没有任何方法的接口。

public interface IMetric {
}

我通过以下方式实现了它。

public class PerfGauge implements IMetric  {

    public PerfGauge(String name, final Object gaugeSource) {

    }
    print() {
         System.out.println("Hello");
    }
}

如何在 PerfGauge class 中调用类型为 IMetric 的方法?我相信这可以通过类型界限来完成?如果可以,有人可以举个例子吗?

我想做的是,

 IMetric metric = new PerfGauge(name,source);
 metric.print();

可以通过反射在任何实例上调用任何方法,但您不应该这样做。

在您的特定用例中:

IMetric metric = new PerfGauge(name,source);
((IPrintable)metric).print();

你可以转换为 PerfGauge:

IMetric metric = new PerfGauge(name,source);
((PerfGauge)metric).print();

...但这不是很令人满意。

我看到了这些更多的即兴选择:

  1. print 添加到 IMetric,因为您似乎需要它,因为您对实例有 IMetric 引用。

  2. 创建第二个独立接口,IPrintable 或其他,print;并让 PerfGauge 实施;然后在您的使用位置使用 IPrintable 而不是 IMetric

    示例如下。

  3. IPrintable 绑定到 IMetric (public interface IPrintableMetric extends IMetric) 以创建 IPrintableMetric 并在其中使用 that您的使用地点:

    IPrintableMetric metric = new PerfGauge(name,source);
    metric.print();
    

根据您在对该问题的评论中提到的限制,听起来独立 IPrintable 可能是可行的方法:

public interface IPrintable {
    void print();
}

public class PerfGauge implements IMetric, IPrintable {

    public PerfGauge(String name, final Object gaugeSource) {

    }
    public void print() {
         System.out.println("Hello");
    }
}

然后:

IPrintable metric = new PerfGauge(name,source);
metric.print();

IMetric metric = new PerfGauge(name,source);
((IPrintable)metric).print();

或者如果您收到没有上下文的 IMetric,则:

if (metric instanceof IPrintable) {
    ((IPrintable)metric).print();
}