简体   繁体   English

可选类中的toString()方法

[英]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). 我想重写其toString()方法,以便与其返回"[Optional(the value)]" ,不如直接返回"(the value)" (如果为空,则返回其他"(the value)" )。 But I can't create a subclass of Optional since it is apparently final. 但是我无法创建Optional的子类,因为它显然是最终的。 How can I do this? 我怎样才能做到这一点?

GhostCat is correct in that you cannot subclass Optional and override its toString method. GhostCat是正确的,因为您不能继承 Optional子类并覆盖其toString方法。 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. 如果存在值,这会将myString设置为值的toString方法的结果,否则,如果不存在该值,它将替换字符串(empty) 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. Optional是最终的,因此在将来的Java版本中将更容易将其转换为值类型 See Project Valhalla for information about value types, in particular State of the Values for an overview and background. 有关值类型的信息,请参阅Valhalla项目,以获取有关概述和背景的信息,尤其是“值的状态”

Optional is also intended to be immutable, so subclassing must be prevented. Optional也打算是不可变的,因此必须防止子类化。 See Bloch, Effective Java , Item 15. 参见Bloch, 有效的Java ,条款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). (是的,其他解释语言可以允许您这样做;但是Java不允许)。

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

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