Is there any way of implementing a StringReader class that allows reusing the same StringReader (or similar functionality) object with more than one strings, without changing any of its functionality (methods)?
For example, such a Java class (say, ReusableStringReader) would be a subclass of java.io.StringReader, with an extra method like
public void reset(String str);
which would assign the new string value to the internal StringReader parameter, so that all subsequent calls to the read() methods of the StringReader use the new value. Such a "reusability" is very convenient when one wants to restrict the number of objects used by an application (e.g., one that handles very large number of strings per second via a Reader object).
General ways to achieve this would be:
- Inheritance. All the internal state of StringReader is stored in private instance variables, so this is not an option.
- Reflection. Reset the internal state of the
StringReaderobject via reflection. There are 4 instance variables to set, which means 4 reflection calls per "reset(String)" call (not too efficient). - Composition. One could use a reusable
StringInputStreamand from that create aReaderobject viaInputStreamReader, then use thatReaderinternally in a subclass ofStringReader, to implement the full API of theStringReaderclass. This is quite a hack, though.
Any ideas for a better solution?