Home > front end >  How to call a Java method from Javascript
How to call a Java method from Javascript

Time:08-02

How do you call a Java method/ function from Javascript?

Java Function:

class Javafunction{

   public static void main(String[] args){

       System.out.println("It Works!");


   }
}

Javascript Function:

  function CallJavafunction() {
    
    Javafunction()

  }

Thanks for answers

CodePudding user response:

To call java code from javascript in your react-native app, you have to create a module

I suggest reading the docs: https://reactnative.dev/docs/native-modules-android

Java code - android/app/src/main/java/com/your-app-name/JavaModule.java

package com.your-app-name; // replace com.your-app-name with your app’s name
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;

public class JavaModule extends ReactContextBaseJavaModule {
   JavaModule(ReactApplicationContext context) {
       super(context);
   }

   @Override
   public String getName() {
       return "JavaModule";
   }

   @ReactMethod
   public void Javafunction(){
       System.out.println("It Works!");
   }
}

Register the Module - android/app/src/main/java/com/your-app-name/MyAppPackage.java

package com.your-app-name; // replace your-app-name with your app’s name
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyAppPackage implements ReactPackage {

   @Override
   public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
       return Collections.emptyList();
   }

   @Override
   public List<NativeModule> createNativeModules(
           ReactApplicationContext reactContext) {
       List<NativeModule> modules = new ArrayList<>();

       modules.add(new JavaModule(reactContext));

       return modules;
   }

}

JavaScript code

const { JavaModule } = ReactNative.NativeModules;
JavaModule.Javafunction();

CodePudding user response:

You cannot do this But you can Calling Java code from a JavaScript adapter

Here Is the Example and documentation : https://www.ibm.com/docs/en/mpf/8.0.0?topic=code-calling-java-from-javascript-adapter

  • Related