In general, this is impossible, because such an array cannot exist inside some ByteString subclasses. BoundedByteString may contain a larger array, so copying is required to get an array of the right size. RopeByteString consists of other byte strings, so copying is required to put the contents in one array. LiteralByteString stores its contents in an array of the required size, but does not provide methods for directly accessing it.
But most likely, toByteArray() will be fast enough for your needs, since System.arraycopy() is very fast.
If you really have a performance problem due to copying large arrays and you do not want to pass ByteString directly, see the asReadOnlyByteBuffer() and asReadOnlyByteBufferList() methods. They complete the ByteString contents in the ByteBuffer without copying.
source share