How to retrieve an object variable in Java Nashorn

I've encountered an issue in my script where I am able to call methods using invokeMethod() in Java, but I'm struggling to access the content of object fields. Below is the JavaScript code snippet:

var Test = { 
    TestVar: "SomeTest", 

    TestFunc: function() {
        print("Hello");
    }
};

In the following Java Class:

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptTest {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        try {
            engine.eval("var Test = { TestVar: \"SomeTest\", TestFunc: function() { print(\"Hello\");}};");
        } catch (ScriptException e) {
            e.printStackTrace();
            System.exit(1);
        }

        System.out.println(engine.get("Test"));
        System.out.println(engine.get("Test.TestVar"));
        System.out.println(engine.get("Test[TestVar]"));
        System.out.println(engine.get("Test[\"TestVar\"]"));

        Invocable inv = (Invocable) engine;

        try {
            inv.invokeMethod(engine.get("Test"), "TestFunc");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

The output obtained from this is:

[object Object]
null
null
null
Hello

My question is whether there is a direct way to access the TestVar variable?

Answer №1

One of the following options should be suitable:

engine.eval("Test.TestVar");

or

((JSObject)engine.get("Test")).getMember("TestVar");

Either approach ought to function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pattern matching to extract multiple numbers within a string

I need help extracting numbers from a string like: There are 1,000 people in those 3 towns. I want to create an array like ["1,000", "3"]. I found a number matching Regex from Justin in this question ^[+-]?(\d*|\d{1,3}(,&b ...

Encountered an unknown tag 13 while trying to build a sequence from byte[]. Unable to complete

Below is the code: import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.openssl.PEMKeyPair; import java.security.KeyPair; import java ...

Comparing the efficiency of AngularJS in generating DOM elements: traditional JavaScript versus jqLite

While working on an AngularJS directive that will display a table with over 1000 rows, my boss advised against using binding due to Angular's limit of around 2000 bindings. Instead, I created the DOM elements dynamically using angular.element(...), wh ...

Trouble with formatting credit card numbers in Vue.js

My payment gateway component includes a feature where selecting credit card triggers the _formatCreditCard method to format the credit card number like this: 4444 2442 4342 3434 This is the function in question: _formatCreditCard: function() { var n ...

Tips for improving the quality of your images

How can I adjust image quality/dpi without changing pixel size? I have an image with a specific pixel size that I need to reduce in quality before saving. If I want to decrease the quality to 87%, how do I achieve this using the following functions? func ...

Maintain the previous value of a DOM element

I'm struggling with the HTML output from a Django render. Here's an example: HTML <div class="treatment container"> <div class="row"> <div class="treatment-phrase col-md-4"> <form action ...

Retrieval of components from JSON array of objects

I have a JSON array containing objects stored on the server. How can I access the first object to print its contents? The data is in the following format: [ { "eventId": "8577", "datasetId": "34", "nodeId": "8076", "typeId": "4", "type": ...

Unable to establish a JDBC connection to MYSQL when using Codename One framework

After creating a basic login form in Java that connects to a MySQL database using a JFrame, I encountered an issue when integrating it into the Codename One application. The JDBC connection is not being accepted. Is there an alternative method that can be ...

Locating an element outside of a class using jQuery

I am trying to target the initial element that matches my criteria OUTSIDE of my container. Even though I can easily find it when it's inside, I struggle when it's outside. My goal is to specifically select the very first element it discover ...

Using the combination of Embedded Jetty and Jersey, it is compatible with Jersey 2.7 but encounters an exception with version 2.9

Currently testing out: How to embed Jetty and Jersey into my Java application When running with Jersey 2.7 (and Jetty 9.2.5.v20141112), it works fine. However, upgrading to Jersey 2.9 (or 2.14) results in a startup failure with the following error: WA ...

Connect various inputs in Vue.js so they can be updated simultaneously

I need to have multiple text inputs that are interconnected, so when I change the value of one input, the others should update with the same value. These inputs are being generated dynamically in a loop using v-for as shown below: <tbody> <varia ...

Identify the appropriate data format

It seems like there is an issue with the code provided. My understanding is that the dayCounter method should receive the dayCheck integer value from the previous code (which is the main method?). In the dayCounter method, this integer should be referred ...

Encountered a Vue.js Vuex error: "Unable to dispatch function in context."

I have implemented a stopwatch function that can run the stopwatch as shown below : Stopwatch.vue <script> export default { data() { return { time: "00:00.000", timeBegan: null, timeStopped: null, stoppedDurat ...

Tips for resolving the error message "TypeError: Converting circular structure to JSON"

I had a straightforward query where I needed to select all from the aliases table. Everything was working fine until I ran npm update. TypeError: Converting circular structure to JSON public async fetchAliases(req: Request, res: Response): Promise< ...

"Utilize Vuejs to establish a binding between two objects when necessary

With the help of moment, my calendar generates 41 days. for (let x = 0; x < 42; x++) { context.add(1, 'd'); let day = { 'date': moment(context), 'events': [] }; } ...

Sorry, the provided text is already unique as it is an error message

I'm currently using the react-highlight-words package to highlight text inputted into a textbox After checking out the react-highlight-words documentation, I noticed that they are using searchWords as an array. https://www.npmjs.com/package/react-high ...

The data-ng-bind directive cannot be used with the <option> tag

Currently, I am in the process of learning angular and encountered a problem that has me stuck. Upon researching on AngularJS : Why ng-bind is better than {{}} in angular?, I found out that both {{}} and ng-bind are said to produce the same result. However ...

Collect various user inputs

I'm having an issue with getting multiple user inputs in my program. I have a function that takes user input based on code from the node.js documentation, but it only allows me to receive one input at a time. How can I modify the code so that I can ge ...

Serve up a 400 error response via the express server when hitting a

I need help serving a 400 error for specific files within the /assets directory that contain .map in their names. For example: /assets/foo-huh4hv45gvfcdfg.map.js. Here's the code I tried, but it didn't work as expected: app.get('/assets&bs ...

Creating a custom icon and static placeholder in a bootstrap dropdown list

I am just starting out in the world of web development and I have been experimenting with creating a dropdown list that includes a static, slightly faded placeholder, along with a custom icon. My goal is to have the selected item's text displayed on t ...