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

Saving the subtracted value from a span into a cookie until the checkbox is unchecked - here's how to

I am working on a piece of code that includes numeric values within a span. When the checkbox is clicked, it subtracts 1 from the main value, essentially reducing the total value. How can I achieve this so that even after the form is submitted, the deducte ...

recurring issues with time outs when making ajax requests

During the development of my website, I tested it as localhost. Now that it's nearly complete, I switched to using my local IP address and noticed that about 30% of my ajax calls result in time out errors or 'failed to load resource errors'. ...

Here are the steps to calculate the duration between two dates in the specified format:

let d1 = new Date("05/20/2022 09:28:15") let d2 = new Date("05/24/2022 12:38:25") Can someone help me calculate the difference between these two dates? ...

What could be the reason for my array parameter not being included in the POST request

When working on my laravel 5.7 / jquery 3 app, I encountered an issue while trying to save an array of data. After submitting the form, I noticed that only the _token parameter is being sent in the POST request as seen in the browser console: let todos_co ...

Exploring the functionality of $timeout in AngularJS

Can you explain the functionality of $timeout in AngularJS and how it sets itself apart from traditional setTimeout()? ...

You cannot use a relative path when inserting an image tag in React

I am having an issue with my img tag not loading the desired image when using a relative src path in my React project. When I try: //import { ReactComponent } from '*.svg'; import React from 'react'; import firebase from "./firebas ...

Utilizing use-immer and promises to effectively handle an API route mapping system

In the process of tackling the issue of double hook calls in Next.js dev mode, I've encountered a challenge with server API calls that cannot handle duplicates. To address this, I opted for fix #4 outlined in the following article, where I decided to ...

Struggling to get getInitialProps working in dynamic routes with Next.js?

I am encountering an issue. The return value from the getInitialProps function is not being passed to the parent component. However, when I console.log the values inside the getInitialProps function, they appear to be correct. Here is the code snippet: i ...

Using jQuery to select the child element of the parent that came before

Recently, I've been experimenting with creating animations using CSS and jQuery. While it has been successful so far, I'm now looking to take it a step further. Specifically, I want information to appear on top of an image when the user clicks on ...

JS Function created to supply elements to React component is failing to return correctly

Trying to validate a dataset by checking for specific prefixes or suffixes in a string, and then breaking the string into <span> elements. The current function correctly identifies the relevant morphemes in the data set, but fails to return the split ...

"Troubleshooting: Node.js encountering a path error while loading a JSON file with

I am organizing a collection of folders and files structured like this: viz |_ app.js // node application |_ public |_ css |_ bubblemap.css |_ images |_ nuts |_ nuts0.json |_ script ...

The TypeScript type 'Record<string, string>' cannot be directly assigned to a type of 'string'

I can't seem to figure out why this code isn't working. I've encountered similar issues in the past and never found a solution. The snippet goes like this: type dataType = { [key: string]: string | Record<string, string>; ...

Is there a way to incorporate HTML code into a fullCalendar 4 event title?

Is it possible to add HTML content to an event title using eventRender in FullCalendar version 4? document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var calendar = new ...

Cannot find the appended element in an AJAX call using jQuery

Within the code snippet, .moneychoose is described as the div in moneychoose.jsp. Interestingly, $(".moneychoose") cannot be selected within the ajax call. $("input[name='money']").on("click", function() { if ($("#money").find(".moneychoose" ...

Is there a way to click on a button and have its background color change randomly each time?

I am facing an issue with a button on my HTML page. When the button is clicked, I want its background color to change to a random different color. However, despite trying various sources, I am unable to get it right. It seems like I am not placing the code ...

The Angular module instantiation failed with the error message: "[$injector:modulerr] Failed to

Struggling with setting up basic AngularJS functionality for a project, especially when trying to include angular-route. Both components are version 1.4.8. My approach involves using gulp-require to concatenate my JS files. Here is my main javascript file: ...

Using JavaScript to call a PHP file as the source file

I'm curious about the scenario where a .php file is called as a javascript. What does this signify and in what situations would it be necessary to use such an approach? Example: <head> <script src="dir/myphpfile.php" type="text/javascript" ...

The state in the React components' array functions is not current

import React, { useState } from "react"; const Person = ({ id, name, age, deleteThisPerson }) => { return ( <div className="person"> <p>{name}</p> <p>{age}</p> <button onClick ...

The customized uploading button functions seamlessly on desktop devices, yet encounters issues when used on

On my website, I have implemented a custom upload button alongside a hidden file input with the class .invisible-file-input. Here is how it is set up: Javascript $('.call-upload').click(function () { $(this).siblings('.invisible- ...

Utilizing destructuring and Object.entries for advanced formatting

I'm embarking on a new React project and facing an issue with the JSON data structure returned by my API for meetings. I attempted to utilize destructuring and Object.entries. This is what I currently have: { "meetings": [ ...