0

I found the post about compiling javascript to java using Rhino compiler. I was able to get the simple case to work and invoke the methods in java. However, I have some questions, and hope I can get them answered here.

  1. How do I compile the below code to TestObject.class with method (setTmpValue,getTmpValue,getType) and constructor of 1 arguments? Or it is not possible?

    function TestObject(params) { this.type= params.type; var tmpValue = 0; this.setTmpValue = function ( val ) { tmpValue = val; }; this.getTmpValue = function () { return tmpValue; }; this.getType = function () { return type }; }

  2. Is it possible to refer a class that will be compiled from other js file?

    Example: Can I invoke B in A? or do new B() in A? A.js -> A.class B.js -> B.class

  3. How does the scope work for these compiled classes?

  4. Is there other documentation than the one Here?

Thanks in advance for helping out!

Community
  • 1
  • 1
jaspercl
  • 1
  • 1

1 Answers1

0

There's an easier way, without compiling; it seems that, given your question and comments, your goal is to have JavaScript objects be callable from Java.

Here's one way to do it:

On Java side:

package mypackage;
public abstract class TestObject {
    // insert public abstract methods
    public abstract void doIt();
}

On JavaScript side:

var myInstance = new JavaAdapter(
    Packages.mypackage.TestObject,
    {
        doIt: function() {
            // do something
        }
    }
)

Packages.myapplication.MyApplication.setTestObject(myInstance);

Back on Java side:

package myapplication;

public class MyApplication {
    private static TestObject test;

    public static void setTestObject(TestObject o) {
        test = o;
    }

    public void doSomething() {
        test.doIt();
    }
}

Basically, JavaScript objects can implement Java interfaces or extend Java abstract classes. If they make themselves available on the Java side, the Java side can call them like Java objects. As far as I can tell, that's what you want. If not, leave a clarification and we'll go from there.

David P. Caldwell
  • 3,394
  • 1
  • 19
  • 32
  • What if you'd like to compile them to `.class` files and cache them to disk so there won't be no need to re-compile the script? I'm looking for something like that. – TheRealChx101 Jul 27 '18 at 16:20