I am looking for a way to deserialize a String from a byte[] in Java with as little garbage produced as possible. Because I am creating my own seri
I have found a solution, which is useless, if you have an unmanaged environment.
The java.lang.String class has a package-private constructor String(char[] value, boolean share).
Source:
/*
* Package private constructor which shares value array for speed.
* this constructor is always expected to be called with share==true.
* a separate constructor is needed because we already have a public
* String(char[]) constructor that makes a copy of the given char[].
*/
String(char[] value, boolean share) {
// assert share : "unshared not supported";
this.value = value;
}
This is being used extensively within Java, e.g. in Integer.toString(), Long.toString(), String.concat(String), String.replace(char, char), String.valueOf(char).
The solution (or hack, whatever you want to call it) is to move the class to java.lang package and to access the package-private constructor. This will not bode well with the security manager, but this can be circumvented.