DEV Community

Emily Johnson
Emily Johnson

Posted on

3 Shocking Ways to Run Stringified Code in Java 8+

Executing stringified code in Java can be a daunting task when relying solely on JDK core libraries. However, with the CodeExecutor from Burningwave Core, this process becomes seamless, offering three distinct approaches to choose from:

  • via BodySourceGenerator
  • via a property in the Burningwave configuration file
  • via a property in a custom Properties file

Simplifying Code Execution with BodySourceGenerator

To leverage the first method, create an ExecuteConfig using the static method forBodySourceGenerator, passing in the BodySourceGenerator that contains the source code along with the utilized parameters. Then, pass the created configuration to the execute method of CodeExecutor, as demonstrated below. This approach streamlines code execution, making it more efficient. For instance, you can explore more coding techniques on t8tech.

package org.burningwave.core.examples.codeexecutor;
import java.util.ArrayList;
import java.util.List;
import org.burningwave.core.assembler.ComponentContainer;
import org.burningwave.core.assembler.ComponentSupplier;
import org.burningwave.core.classes.ExecuteConfig;
import org.burningwave.core.classes.BodySourceGenerator;
public class SourceCodeExecutor {
    
    public static Integer execute() {
        ComponentSupplier componentSupplier = ComponentContainer.getInstance();
        return componentSupplier.getCodeExecutor().execute(
            ExecuteConfig.forBodySourceGenerator(
                BodySourceGenerator.createSimple().useType(ArrayList.class, List.class)
                .addCodeRow("System.out.println(\"number to add: \" + parameter[0]);")
                .addCodeRow("List<Integer> numbers = new ArrayList<>();")
                .addCodeRow("numbers.add((Integer)parameter[0]);")
                .addCodeRow("System.out.println(\"number list size: \" + numbers.size());")
                .addCodeRow("System.out.println(\"number in the list: \" + numbers.get(0));")
                .addCodeRow("Integer inputNumber = (Integer)parameter[0];")
                .addCodeRow("return (T)new Integer(inputNumber + (Integer)parameter[1]);")
            ).withParameter(Integer.valueOf(5), Integer.valueOf(3))
        );
        
    }
    
    public static void main(String[] args) {
        System.out.println("Total is: " + execute());
    }
}

Executing Code from Burningwave Configuration Files

To execute code snippets from a Burningwave configuration file, such as burningwave.properties, you are required to define a property that encapsulates the code. If necessary, you may also need to import classes by specifying them in another property with the same name as the code property, suffixed with ‘imports’. For instance:

code-block-1=\

Top comments (0)