Skip to content

Instantly share code, notes, and snippets.

@mikesamuel
Created June 3, 2021 13:43
Show Gist options
  • Save mikesamuel/3b8478e2811eb54efed7b2a32b2d23da to your computer and use it in GitHub Desktop.
Save mikesamuel/3b8478e2811eb54efed7b2a32b2d23da to your computer and use it in GitHub Desktop.
Java boxing is violable
import java.lang.reflect.*;
import java.util.*;
public class Foo {
public static void main(String[] argv) throws Exception {
Class<?> integerCacheClass = Arrays.stream(Integer.class.getDeclaredClasses())
.filter(c -> c.getSimpleName().equals("IntegerCache"))
.findFirst()
.get();
Field cacheField = Arrays.stream(integerCacheClass.getDeclaredFields())
.filter(c -> c.getName().equals("cache"))
.findFirst()
.get();
cacheField.setAccessible(true);
Integer[] cache = (Integer[]) cacheField.get(null);
Arrays.fill(cache, new Integer(1337));
Integer boxed = 3;
System.out.println("" + boxed);
}
}
@mikesamuel
Copy link
Author

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by Foo (file:/private/tmp/) to field java.lang.Integer$IntegerCache.cache
WARNING: Please consider reporting this to the maintainers of Foo
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
1337

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment