CharSequenceAccessor { static public CharArrayWrapper access(CharSequence str) { if (str == null) { return null; } try { if (str instanceof String) { if (hasStringFields) { CharArrayWrapper w = new CharArrayWrapper(); w.value = (char[])stringValueField.get(str); w.offset = stringOffsetField.getInt(str); w.length = stringCountField.getInt(str); return w; } } else if (str instanceof StringBuilder) { if (hasStringBuilderFields) { CharArrayWrapper w = new CharArrayWrapper(); w.value = (char[])stringBuilderValueField.get(str); w.length = stringBuilderCountField.getInt(str); return w; } } } catch (Throwable t) { } return null; }  static CharArrayWrapper access(CharSequence str); static String createOptimizedString(char[] buffer, int offset, int length); static void updateStringBuilder(StringBuilder sb, int newLength);  }
@Test public void usage() throws Exception { try { String s0 = "test"; CharArrayWrapper wrapper = CharSequenceAccessor.access(s0); Assert.assertEquals(0, wrapper.offset); Assert.assertEquals(4, wrapper.length); Assert.assertArrayEquals(new char[] { 't','e','s','t' }, wrapper.value); String s1 = s0.substring(1); wrapper = CharSequenceAccessor.access(s1); Assert.assertEquals(1, wrapper.offset); Assert.assertEquals(3, wrapper.length); Assert.assertArrayEquals(new char[] { 't','e','s','t' }, wrapper.value); StringBuilder sb = new StringBuilder("test"); wrapper = CharSequenceAccessor.access(sb); Assert.assertEquals(0, wrapper.offset); Assert.assertEquals(4, wrapper.length); Assert.assertArrayEquals(new char[] { 't','e','s','t' }, Arrays.copyOf(wrapper.value, 4)); StringBuffer sbf = new StringBuffer("test"); wrapper = CharSequenceAccessor.access(sbf); Assert.assertNull(wrapper); } catch (Throwable t) { System.out.println("WARN: CharSequenceAccessor tests failed... optimizations disabled"); } }