Expanding Java Classes and Replacing Methods with Multiple Parameters in ES4X/Graal

I am currently facing a challenge in my JavaScript project using ES4X/Graal, where I need to extend a Java class. This Java class has methods with overloaded parameters that I must override. While I understand how to call a specific Java method by specifying the type in square brackets, it seems that there is no clear way to specify parameter types when overriding based on the Graal/Oracle/Nashorn documentation. For example:

package com.mycomp;

class A {
    public void method(String parameter) {...}
    public void method(int parameter) {...}
}

In JavaScript, calling these methods can be done as follows:

var a = Java.type("com.mycomp.A");

a["method(String)"]("Some string parameter")
a["method(int)"](42)
a.method(stringOrIntParam)

However, during extension, the options are limited:

var ClassAFromJava = Java.type("com.mycom.A");
var MyJavaScriptClassA = Java.extend(ClassAFromJava, {
    method: function(stringOrIntParam) {...}
}

I desire the ability to extend only one of the "method(...)" methods. Additionally, how would this work for overloaded methods with distinct return types?

Thank you!

Answer №1

Utilizing the sj4js framework enables you to achieve all of this.

This specific scenario is slightly adjusted from the official documentation...

public class TestObject extends JsProxyObject {
    
    // constructor containing the property 
    public TestObject (String name) {
        super ();
        
        this.name = name;
        
        // initialization of the proxy object
        init(this);
    }

    // mandatory override method for the proxy object functionality 
    @Override
    protected Object newInstance() {
        return new TestClass(this.name);
    }

    // method with a String parameter
    public String method (String s) {
        return "String";
    }

    // method with an int parameter
    public String method (int i) {
        return "42";
    }
}

You can interact with this object as if it were a JS object, and the library handles selecting the appropriate method.

try (JScriptEngine engine = new JScriptEngine()) {
    engine.addObject("test", new TestClass("123"));
            
    // invoking the method with the String parameter will 
    // execute the corresponding java method
    engine.exec("test.method('123')");
    // returns "String"

    // invoking the method with the int parameter will 
    // execute the relevant java method
    engine.exec("test.method(123)");
    // returns "42"
}

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

Using Flickity API in Vue 3 with Typescript Integration

I have encountered an issue with implementing Flickity in my Vue 3 application. Everything works perfectly fine when using a static HTML carousel with fixed cells. However, I am facing difficulties when attempting to dynamically add cells during runtime us ...

Iterating through elements within the ng-content directive in Angular using *ngFor

Is it possible to iterate through specific elements in ng-content and assign a different CSS class to each element? Currently, I am passing a parameter to enumerate child elements, but I would like to achieve this without using numbers. Here is an example ...

finding the initial element within an object using lodash in javascript

Recently, I came across some data in the form of an array of objects. For instance, let me share a sample dataset with you: "data": [ { "name": "name", "mockupImages": "http://test.com/image1.png,http://test.com/image2.png" }] ========================== ...

Implementing mock methods with JUnit and Mockito

I have been attempting to test the following class: public class PreprocessorServiceImpl implements PreprocessorService { private static final Logger LOG = LoggerFactory.getLogger( PreprocessorServiceImpl.class ); private FileServiceProvider fileService ...

What is the best way to implement client-side shopping cart calculations using jQuery?

https://i.stack.imgur.com/aOajr.png Here is the content of my shopping cart. Below, I will explain the flow. [product image clicked] -> ajax request fetches details from database for that particular product id and appends (product name,id and price ...

Having trouble with Javascript in getting one-page scroll navigation to work?

Hey there, I am working on creating a one-page scroll navigation with some basic javascript to add a smooth animation effect that takes 1 second as it scrolls to the desired section. However, I seem to be experiencing an issue where it's not functioni ...

Is there a way to calculate the mean of radio buttons that each have their own distinct values?

My HTML page features a unique rating system created with radio buttons that resemble stars when filled in. The CSS styling gives them an appealing design. Additionally, I have included a submit button to display the selected star count when clicked. Here ...

The chosen index in the Material Stepper feature is experiencing a malfunction

I've been busy working on a Mat-Stepper, actually two of them. I have a component that contains two ng-templates set up like this: Question: Why is my selected index not functioning as expected? Am I missing something? I know you can define [selected ...

Every time you attempt to download in Vue, you are met with the familiar sight

Encountering a peculiar issue while attempting to download an apk file using a Vue.js website: Referring to How to download a locally stored file in VueJS, I am trying to download a local file with this command: <a href="../../app-debug.apk" download= ...

Is there a way to update the background image of a div element through a JavaScript file within a react component?

After spending hours on this issue, I am still stuck and have exhausted all my ideas and research. In my project, I have three buttons that are supposed to change the background image of my site. The background image is linked to the default "App" div elem ...

Animating a CSS shape with the .animate method

I need help creating a dynamic graphic for my school project using css, jquery, and html. I want to make a rectangle that moves across the screen, but I'm having trouble getting it to work properly. Despite trying different variations of the animate f ...

Using ReactJS to incorporate events with an external DOM element

I am using ReactJS version 16.13.1 and I have the need to display an external DOM element along with its events. Let's consider having a <button type="button" id="testBtnSiri" onclick="alert('Functionality exists');">Testbutton Sir ...

Building a Next.js application in a docker container on a local machine using minikube is successful, however, the build fails when attempting to build it on a staging environment

I've encountered a puzzling issue. My next.js app is running in a docker container. It builds successfully on my local Ubuntu machine with minikube and ks8 orchestration, but it gets stuck indefinitely during the build process on the staging setup. T ...

What is the best way to superimpose an image onto a canvas?

I am working on a cool project where I have created a canvas that displays matrix binary code raining down. However, I would like to enhance it by adding an image overlay on top of the canvas. Here is my current setup: <div class="rain"> ...

Setting radio button selection programmatically in React Material-UI: A step-by-step guide

Currently utilizing a radio button group from material-ui. I have successfully set a default selection using defaultSelected, however, after rendering, I am unable to programmatically change it. The selection only updates upon clicking the radio. Is ther ...

Unable to resize static and draggable elements simultaneously

Observe this fiddle to see the demonstration: DEMO If you are interested in the resizing of white divs, check out this link: Resizing of White divs The draggable divs are represented by red while the static divs are shown in white and located in droppabl ...

Ways to discover the titles of every sub-directory

Suppose I have the absolute path of a directory. Is there a method in JavaScript (Node.js) to determine how many sub-directories it has, and retrieve the names of all its sub-directories? I searched online but didn't come across any solution. ...

Adjust the size of the Threejs canvas to fit the container dimensions

Is there a way to determine the canvas size based on its container in order to prevent scrolling? Setting the size based on the window results in the canvas being too large. ...

Unexpected behavior encountered in Rails app with unobtrusive JavaScript

I'm facing an issue with my link_to setup. Here's what I have: <%= link_to "Load More", comments_feed_path(@post.id), :id => 'my-link', :remote => true %> In my application.js file, I have the following code: $( document ...

Save the status of checkboxes in a JSON file using boolean values of true or false

When a user submits a form, I am retrieving the values of checkboxes and storing them as an array. The simplified form structure is as follows: <!-- gym_create.html - other input fields are omitted for brevity --> <form class="create-gym" role=" ...