我在写一个方法,要求它的某个参数从特定类(MyClass
)下降并实现一个接口(MyInterface
)。指定方法参数必须从一个类继承并实现接口
这样做的一种粗暴的方式将
public void doStuff(MyClass arg0) {
if (!(arg0 instanceof MyInterface))
throw new IllegalArgumentException("arg0 must implement MyInterface");
// do whatever we need to do
}
注意MyClass
没有实现MyInterface
,都是我进口,因为它们的类。
是否有更好的方法来做到这一点,最好是在构建时已经标记错误的方法?
'public void doStuff(MyInterface someclass)'?那么只需让MyClass实现MyInterface? –
@blahfunk这两个类只是进口,所以这不是一个选项。我澄清了这个问题。 – user149408