Skip to main content

Code injection prevention for Java

This is a code injection prevention cheat sheet by Semgrep, Inc. It contains code patterns of potential ways to run arbitrary code in an application. Instead of scrutinizing code for exploitable vulnerabilities, the recommendations in this cheat sheet pave a safe road for developers that mitigate the possibility of code injection in your code. By following these recommendations, you can be reasonably sure your code is free of code injection.

Check your project using Semgrep

The following command runs an optimized set of rules for your project:

semgrep --config p/default

1. Unsafe Reflection

1.A. Using unsafe reflection with user input in Class.forName

The Class.forName function returns the Class object for the class or interface with the name as a string. If an attacker supplies values that the application then uses to determine which class to instantiate or which method to invoke, the attacker can instantiate classes that the application developers did not intend. This can lead to unexpected behavior. For example, broken authentication that results in access to private data, or otherwise allow the attacker to obtain control of application behavior causing the application to behave in an unexpected manner.


String userInput = "org.pwned.package"; // value supplied by user input
Class<?> loadClass = Class.forName(userInput + ".AttackerThread");



  • Try to avoid non-literal values in the first argument of Class.forName() such as Class.forName(userInput + ".AttackerThread").
  • If it is not possible, use an allowlist for inputs.

Semgrep rule