Java 使用类型边界在接口中不存在的类中调用方法
我有下面的界面,没有任何方法Java 使用类型边界在接口中不存在的类中调用方法,java,oop,types,interface,type-bounds,Java,Oop,Types,Interface,Type Bounds,我有下面的界面,没有任何方法 public interface IMetric { } 我用以下方式实现了它 public class PerfGauge implements IMetric { public PerfGauge(String name, final Object gaugeSource) { } print() { System.out.println("Hello"); } } 如何在PerfGauge类中调用类型
public interface IMetric {
}
我用以下方式实现了它
public class PerfGauge implements IMetric {
public PerfGauge(String name, final Object gaugeSource) {
}
print() {
System.out.println("Hello");
}
}
如何在PerfGauge类中调用类型为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();
…但这不是很令人满意
我看到了这些现成的进一步选择:
print
添加到IMetric
,因为您在引用实例的IMetric
位置似乎需要它print
创建第二个独立接口,IPrintable
或其他任何接口;并让PerfGauge
实现该功能;然后在使用位置使用IPrintable
而不是IMetric
下面的例子IPrintable
绑定到IMetric
(公共接口IPrintableMetric扩展IMetric
)以创建IPrintableMetric
,并在您的使用位置使用它:
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
,则:
if (metric instanceof IPrintable) {
((IPrintable)metric).print();
}
为什么不将
print
添加到IMetric
?如果该方法不在接口中,则只能通过将metric
变量强制转换为实现类的类型来调用它。我认为类型边界与上述无关,至少与上述上下文无关。“还有许多其他实现具有其他方法”然后我想你可以使用我列表中的选项2或选项3将它们分为“可打印”和“不可打印”两类。如果接口没有描述你试图调用的成员,你为什么要使用接口?现在还不清楚你的实际需求是什么。仅仅说“一些内部需求”根本无助于澄清这一点
if (metric instanceof IPrintable) {
((IPrintable)metric).print();
}