Java: String
↔char[]
Posted by Michał ‘mina86’ Nazarewicz on 9th of February 2019 | (cite)
Do you recall when I decided to abuse Go’s runtime and play with string
↔[]byte
conversion? Fun times… I wonder if we could do the same to Java?
To remind ourselves of the ‘problem’, strings in Java are immutable but because Java has no concept of ownership or const
keyword to make true on that promise, Java runtime has to make a defensive copy each time a new string is created or when string’s characters are returned.
Alas, do not despair! There is another way (exception handling elided for brevity):
private static Field getValueField() { final Field field = String.class.getDeclaredField("value"); field.setAccessible(true); /* Test that it works. */ final char[] chars = new char[]{'F', 'o', 'o'}; final String string = new String(); field.set(string, chars); if (string.equals("Foo") && field.get(string) == chars) { return field; } throw new UnsupportedOperationException( "UnsafeString not supported by the runtime"); } private final static Field valueField = getValueField(); public static String fromChars(final char[] chars) { final String string = new String(); valueField.set(string, chars); return string; } public static char[] toChars(final String string) { return (char[]) valueField.get(string); }
However. There is a twist…