简体   繁体   English

覆盖stringBuilder中的append方法?

[英]Overriding append method in stringBuilder?

I have a question regarding the append method in the StringBuilder class. 我对StringBuilder类中的append方法有疑问。 I was asked how can we override the append() method in the StringBuilder class while stringBuilder class is final. 我被问到,当stringBuilder类是最终的时,我们如何覆盖StringBuilder类中的append()方法。 Is the same logic applicable for overriding toString() in String class while String class is final? 相同的逻辑适用于在String类为final时覆盖String类中的toString()吗? Please help me. 请帮我。

Thanks 谢谢

No, you can't really override a final method, there might be some bytecode level magic that would allow you to do that, but I'm not sure it is worth it. 不,您无法真正覆盖final方法,可能有些字节码级别的魔术可以让您做到这一点,但我不确定是否值得。

You can create a wrapper class, something like MyStringBuilder and for every one of the methods in StringBuilder create a method that delegates to an instance of StringBuilder , then you can modify the append methods as you see fit. 您可以创建一个包装器类(类似于MyStringBuilder并为StringBuilder每个方法创建一个委托给StringBuilder实例的方法,然后可以根据需要修改append方法。 There is a catch with this approach and that is that you can't access private variables defined in StringBuilder although that might not be such a big deal for your use case. 这种方法有一个问题,那就是您不能访问StringBuilder定义的private变量,尽管这对于您的用例而言可能并不重要。 YMMV 因人而异

A class declared final can't be extended, so there is no way to override any method of it. 声明为final的类无法扩展,因此无法覆盖它的任何方法。

A class which is not declared final can be extended, but any method declared final can't be overridden. 可以扩展未声明为final类,但不能重写任何声明为final方法。

Overriding toString in the String class is overriding a method of java.lang.Object in java.lang.String . 覆盖String类中的toString覆盖了java.lang.Objectjava.lang.String的方法。 Since the class is declared final, you can't derive from it and hence not override the toString-method, which is a special case in String, since it returns the String itself. 由于该类被声明为final,因此您不能从该类派生,因此也不能覆盖toString方法,这在String中是一种特殊情况,因为它返回String本身。

Overriding a method in a final class is impossible. 在最终类中重写方法是不可能的。 And append () isn't a method in Object, so they are not equivalent, but you can't override append either. 而且append ()不是Object中的方法,因此它们不是等效的,但是您也不能覆盖append。

Those classes are final by design. 这些课程是最终设计的。 The API designers didn't want to deal with the added complexity of making those classes a base class for inheritance. API设计人员不想处理使这些类成为继承基类的额外复杂性。

Instead of inheritance, you can use delegation and create your own StringBuilder class that uses an instance of java.lang.StringBuilder as delegate. 除了继承以外,还可以使用委托并创建自己的StringBuilder类,该类将java.lang.StringBuilder的实例用作委托。 This makes it trivial to create your own append methods. 这使得创建自己的append方法变得很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM