Java: design interface to force implementations to override toString

左心房为你撑大大i 提交于 2019-11-30 22:26:54

问题


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.

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()
    {
        // ...
    }
}

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.


回答1:


No, you can't do this. I'd suggest you choose a different method name, e.g.

public interface Reportable
{
    String createReport();
}

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.




回答2:


What I understand is that you want to create a set of classes which neatly give their string representations. So that when something like System.out.println(yourobject) is called it shows meaningful data.

You cannot force your subclasses to override toString. But you can do something like this.

abstract class MyBase
{
    abstract String getNiceString();
    @Override
    public String toString()
    {
        return getNiceString();
    }
}


来源:https://stackoverflow.com/questions/10054403/java-design-interface-to-force-implementations-to-override-tostring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!