{{announcement.body}}
{{announcement.title}}

Executing Stringified Source Code in Java 8 and Later

DZone 's Guide to

Executing Stringified Source Code in Java 8 and Later

In this article take a look at how to execute a string that contains source code in Java 8 and later.

· Java Zone ·
Free Resource

Executing stringified source code in Java is hard to realize with only jdk core libraries but, if we are going to use the CodeExecutor of Burningwave Core, the task will become simple and we can accomplish it in one of three different ways that we can choose:

  • through BodySourceGenerator
  • through a property located in Burningwave configuration file
  • through a property located in a custom Properties file

Executing Code With BodySourceGenerator

For the first way, we must create a ExecuteConfig by using the within static method forBodySourceGenerator to which must be passed the BodySourceGenerator that contains the source code with the parameters used within: after that we must pass the created configuration to the execute method of CodeExecutor as shown below:

Java


Executing Code of a Property Located in Burningwave Configuration File

To execute code from Burningwave configuration file (burningwave.properties or another file that we have used to create the ComponentContainer: see architectural overview and configuration) we must add to it a property that contains the code and, if it is necessary to import classes, you must add them to another property named as the property that contains the code plus the suffix 'imports'. E.g:

Properties files


It is also possible to include the code of a property in another property:

Properties files


After that, for executing the code of the property, we must call the executeProperty method of CodeExecutor and passing to it the property name to be executed and parameters used in the property code:

Java


Executing Code of a Property Located in a Custom Properties File 

To execute code from a custom properties file we must add to it a property that contains the code and, if it is necessary to import classes, we must add them to another property named as the property that contains the code plus the suffix 'imports'. E.g:

Properties files


It is also possible to include the code of a property in another property:

Properties files


After that, for executing the code of the property we must create an ExecuteConfig object and set on it:

  • the path (relative or absolute) of our custom properties file
  • the property name to be executed
  • the parameters used in the property code

Then we must call the execute method of CodeExecutor with the created ExecuteConfig object:

Java


Topics:
code, execute, java, properties, strings, tutorial

Published at DZone with permission of Oscar Strand . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}