Selective setAccessible permissions using Byte Buddy and the Java SecurityManager
The Java SecurityManager provides a lot of good permissions for restricted what untrusted code can access. The downside of the standard permissions is that many of them are too broad, making it hard to enable permissions around commonly used functionality without defeating the purpose of the restricted security. The permissions around reflections are one of these cases, where the permissions around the setAccessible reflections method is either all on or all off. It is possible to work around this default behavior, providing more selective fine-grained permissions, by using bytecode weaving. However, for any of this this to work the Java SecurityManager must be used along with loading the code that these permissions will be applied to from a separate jar, probably using a custom or at least isolated instance of a URLClassLoader. This is a prerequisite which has already been well documented by Will Sargent in his post Self-Protecting Sandbox Using SecurityManager as well as my own example sandbox runtime environment sandbox-runtime.