问题描述
我正在开发一个SPI,并希望定义一个可报告的
接口,这样任何实现都必须覆盖 toString()
到有意义的东西。
I'm developing an SPI and would like to define a Reportable
interface such that any implementations must override toString()
to something that is meaningful.
在Java中有没有办法编写一个接口,使得它的任何具体实现必须覆盖Object的的toString()
?例如:
Is there any way in Java to write an interface such that any of its concrete implementations must override Object's toString()
? For instance:
public interface Reportable
{
public String toString();
}
public class Widget implements Fizz, Buzz, Reportable
{
// ...
@Override
public String toString()
{
// ...
}
}
我知道上面的代码没有强制这种行为,但是我正在寻找的一个例子,即如果 Widget
不会覆盖 toString()
您收到编译错误,因为它违反了接口合同。
I know the above code doesn't force this kind of behavior, but is an example of what I'm looking for, i.e. if Widget
doesn't override toString()
you get a compile error because its violating the interface contract.
推荐答案
不,你不能这样做。我建议您选择不同的方法名称,例如
No, you can't do this. I'd suggest you choose a different method name, e.g.
public interface Reportable
{
String createReport();
}
这将强制实现编写适当的方法。 toString()
的意图已经有些模糊 - 无论是用于调试表示,用户可见的表示(此时你需要问自己有关语言环境等)。添加另一个意义对我来说似乎不是一个好主意。
That will force implementations to write an appropriate method. toString()
is already somewhat vague in its intention - whether it's for debug representations, user-visible representations (at which point you need to ask yourself about locales etc). Adding another meaning doesn't seem like a good idea to me.
这篇关于Java:强制实现覆盖toString的设计接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!