mardi 21 janvier 2020

Messing with String class fields with reflection in Android

Sometimes I like to mess with reflection just for the sake of it. Sorry if this is too broad. Could somebody explain to me what are the values I'm getting here in this code? This is running on Android.

private static void test() {
    try {
        String sVal = "Hello!";
        try {
            sVal.charAt(6);
        } catch (StringIndexOutOfBoundsException ex) {
            // This will happen
            ex.printStackTrace();
        }
        Field f = String.class.getDeclaredField("count");
        f.setAccessible(true);
        f.set(sVal, 10000);
        // Now, this won't fail
        sVal.charAt(6);
        byte[] buffer = sVal.getBytes();
        Log.v("Test", "buff.length = " + buffer.length); // buffer.length == 5465 ??
        String s = new String(buffer); // buffer now apparently contains random parts of memory
        Log.v("Test", "" + s);
    } catch (Throwable t) {
        t.printStackTrace();
    }
}




Aucun commentaire:

Enregistrer un commentaire