Skip to content

Instantly share code, notes, and snippets.

@LukasForst
Last active September 10, 2020 08:37
Show Gist options
  • Save LukasForst/0363c1dad1739c5cd5a4171efcf9823b to your computer and use it in GitHub Desktop.
Save LukasForst/0363c1dad1739c5cd5a4171efcf9823b to your computer and use it in GitHub Desktop.
Rewriting integer cache in Java - explanation here https://javapapers.com/java/java-integer-cache/
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
final Class cache = Integer.class.getDeclaredClasses()[0];
final Field cacheField = cache.getDeclaredField("cache");
cacheField.setAccessible(true);
final Integer[] array = (Integer[]) cacheField.get(cache);
array[132] = 5;
assert 5 == 2 + 2;
// prints 5
System.out.printf("%d\n", 2 + 2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment