Quantcast
Channel: Coffeewithcode.com
Viewing all articles
Browse latest Browse all 40

How To Call A Java Script From Java Code?

$
0
0

This post is to describe how to call a java script from java code.

Below is  java file.In which there is a main method.In this main method a script engine instance is taken.This script engine is already with jdk.For this one need not to add any other jar file.

  1. import java.io.FileNotFoundException;
  2. import java.io.FileReader;
  3.  
  4. import javax.script.ScriptEngine;
  5. import javax.script.ScriptEngineManager;
  6. import javax.script.ScriptException;
  7.  
  8. public class Driver {
  9.  
  10. /**
  11. * @param args
  12. * @throws FileNotFoundException
  13. */
  14. public static void main(String[] args) throws FileNotFoundException {
  15. try {
  16. /**
  17. * To call a anonymous function from java script file
  18. */
  19. ScriptEngine engine = new ScriptEngineManager()
  20. .getEngineByName("javascript");
  21. FileReader fr = new FileReader("src/js/MySpec.js");
  22. engine.eval(fr);
  23.  
  24. } catch (ScriptException scrEx) {
  25. scrEx.printStackTrace();
  26. }
  27. }
  28. }

Below is the java script file with an anonymous fuction.This function is to print on the console.

  1. // java script anonumous function
  2. (function() {
  3. print('Hello world');
  4. })();

Below is the folder structure of the project.

Folder Structure

Folder Structure

Your Suggestions Are Always Welcomed.


Viewing all articles
Browse latest Browse all 40

Trending Articles