If security is a concern, is it actually safe to use reflection to trigger methods [...] or would it be preferable to simply hardcode calls to method names?
In general, it is preferable to NOT use reflection because your application will be faster, simpler (e.g. fewer lines of code) and less fragile; i.e. less likely to throw unchecked exceptions. It is best to only use reflection when simpler approaches won't work.
Security of reflection is also a potential concern.
If your JVM is running untrusted or unknown code that might try to do bad things, then the reflection APIs in general offer lots of opportunities to do bad things. For example, it allows the bad code to call methods and access fields that the Java compiler would prevent. (It even allows the code to do evil things like changing the value of final
attributes and other things that are normally assumed to be immutable.)
Even if your JVM is running entirely trusted code, it is still possible that a design flaw or system-level security problem may allow the injection of class or method names by a hacker. The reflection APIs would then dutifully attempt to invoke unexpected methods.
If reflection is a potential issue, how would one prevent it?
That is easy. An application requires various permissions to successfully call the relevant security sensitive methods in the reflection APIs. These permissions are granted by default to trusted applications and not to sandboxed applications. You are free to adjust them.
The simple solution: if you are running trusted code, or if you are worried about the possibility of design flaws comprising security, run all relevant code in a security sandbox that prevents use of the reflection APIs. (The downside is that some 3rd-party libraries are designed under the assumption that they can use reflection ... and will break in a sandbox.)
(Apparently, there is no permission check for an actual Method.invoke(...)
call. The check happens earlier when the application code obtains the Method
object from the Class
.)