If security is a problem, is it safe to use reflection to invoke methods [...] or would it be preferable to just query the method names hard?
In general, it is preferable NOT to use reflection. Your application will be faster, easier (for example, fewer lines of code) and less fragile (for example, less likely to throw excluded exceptions) if you use regular (non-reflective) calls. It is best to use reflection when simpler approaches will not work.
Reflection safety is also a potential concern.
If your JVM runs untrusted or unknown code that might try to do bad things, then reflection APIs generally offer many possibilities for creating bad things. For example, it allows bad code to invoke methods and access fields that the Java compiler will prevent. (It even allows code to do evil things, such as changing the value of final attributes and other things that are usually considered immutable.)
Even if your JVM is running with fully trusted code, it is still possible that a design problem or a system security issue may allow the injection of a class or method name by a hacker. Then reflection APIs will obediently try to invoke unexpected methods.
If reflection is a potential problem, how can this be prevented?
It is easy. The application requires various permissions to successfully invoke the appropriate security-sensitive methods in the reflection API. These permissions are granted by default to trusted applications, not stand-alone applications. You can adjust them.
A simple solution: if you are using reliable code, or if you are concerned about the possibility of design errors that contain security, run all the relevant code in a security sandbox that prevents the use of the reflection API. (The disadvantage is that some third-party libraries are designed under the assumption that they can use reflection ... and will break into a sandbox.)
(Apparently, there is no verification of the actual call to Method.invoke(...) . Verification occurs earlier when the application code gets the Method object from Class .)
source share