Java Reflection – How to Make an Object/Class Inaccessible to Reflection

code-securityjavareflection

I am building an API for minecraft called the Quantum API. We all know that reflection can be used to do some nasty stuff to classes, and even cause undefined behavior if used without care.

Is there a way to make classes and objects immune to reflection? Perhaps with a security manager? Or vice versa, restrict a certain list of classes/objects from using reflection?

My use would be to prevent other mods that are loaded with this API from using reflection to change a RuntimePermission in a SecurityManager, and to prevent modification of minecraft's base classes (and objects) at runtime, as well as the API's own classes (and objects).

Best Answer

I would suggest using obfuscation. It doesn't prevent reflection, but it'll make it practically impossible (technically, someone could still do it but it'll take them far more effort to figure it all out) for someone to figure out what part of the code does what, as it'll (amongst other things) scramble the names of functions.

You can usually set exclusions, such as functions that need to be publically accessible for an API.

Unfortunately, it'll only work for your own code, and not Minecraft itself, but it's the best practical solution I can think of.

Otherwise, I think there might be a solution that involves making your own custom loader for Minecraft with a SecurityManager that sandboxes everything and prevents reflection, but I'm not entirely sure if that's possible. You may want to look at this question on StackOverflow which discusses that possibility further.

Related Topic