As you may know Java is not a scripting language, but it is possible to execute scripts written in scripting languages like JavaScript or Groovy using the Nashorn Scripting Engine.
Let us see a very basic "hello world" example:
package org.code2care.java.examples;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Main {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
String javaScript = "var message = 'Hello Java from JavaScript!'; print(message);";
engine.eval(javaScript);
}
}
The Java Scripting API is a built-in feature of Java that allows you to execute scripts written in various languages, including JavaScript, Groovy, Ruby, and Python.
ScriptEngine is the class that you will create an instance of passing in the scripting language that you want to use, and make use of the eval() method to execute the script.
-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Java,
- CRUD operations in Spring Boot + JDBC
- Java Check Leap Year - Programs with Code Examples
- [fix] Java JDBC ConnectException: Connection refused
- How to add hours and minutes to Java Instant
- Java Program: Random Number Generator
- Java: The value of the local variable string is not used
- How to get list of all Java versions installed on macOS
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Java + Spring JDBC Template + Gradle Example
- Convert String to LocalDate in Java
- Remove Trailing zeros BigDecimal Java
- Java 8 Predicate Functional Interface isEqual() Method Example
- How to Hardcode Date in Java with Examples
- Java 8: Predicate negate() default Function Example
- Java: Collect Stream as ArrayList or LinkedList
- The Motivation Behind Generics in Java Programming
- How to Add/Subtract Days to the Current Date in Java
- Error: Can not find the tag library descriptor for
- Setting up JUnit 5 dependency with Maven Example
- Run Java Code Every Second
- How to create a tar.gz file using Java
- [Fix] java: integer number too large compilation error
- Java 8: Find the Max value in a List
- Your JBoss Application Server 7 is running However you have not yet added any users to be able to access the admin console
- Convert Java Array to ArrayList Code Example
More Posts:
- How to Update Roblox on Mac - MacOS
- 21 Essential Mac Terminal Shortcuts for Devs and DevOps to Boost Productivity - MacOS
- Where are Notepad++ macros stored? - NotepadPlusPlus
- [Fix] MySQL Docker ERROR 1045 (28000): Access denied for user root@localhost (using password: YES/NO) - MySQL
- Change Mac Terminal Font Size using Command - MacOS
- Android Studio : Connection Error : Failed to download patch file - Android-Studio
- Google Search Hot Trends Screensaver for Mac OS X - MacOS
- Setting Up VS Code with Java JDK 21 - Java-JDK-21