简体   繁体   中英

override toString() method in class Optional

I have an instance variable defined as:

final Optional<myClass> myOptional; 

I would like to override its toString() method so that instead of returning "[Optional(the value)]" it simply returns "(the value)" (or something else if it's empty). But I can't create a subclass of Optional since it is apparently final. How can I do this?

GhostCat is correct in that you cannot subclass Optional and override its toString method. However, you can probably get the effect you want by writing this:

String myString = myOptional.map(MyClass::toString).orElse("(empty)")

This sets myString to the result of the value's toString method if a value is present, otherwise it substitutes the string (empty) if the value is absent. Of course, you can put whatever substitute string you want there.

Optional is final so that it will be easier to convert into a value type in a future version of Java. See Project Valhalla for information about value types, in particular State of the Values for an overview and background.

Optional is also intended to be immutable, so subclassing must be prevented. See Bloch, Effective Java , Item 15.

You can't.

There is no way of changing the behavior of methods of a class from outside its source code. So, the only choices you got are:

  1. Turn to the source code of that class and make changes there
  2. Extend the class, override the method and then use objects of the derived class

In your case, both options not possible. Sorry, end of story.

(yes, other, interpreted languages would allow you to do so; but Java does not).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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