This is a basic example where we call a Java class from a .NET (6/7/Framework) application. This example consider:
Let’s consider a Java code like the following one:
public class JavaClass { /** * This simple method return the "Hello World!!" string * * @return "Hello World!!" string */ public String helloWorld() { return "Hello World from Java!!"; } /** * This simple method return the sum of two double * @param a * @param b * @return a + b */ public double add(double a, double b) { return a+b; } /** * This simple method return the sin of a double * @param a * @return sin of a */ public double sin(double a) { return Math.sin(a); } }
Create a folder and save the above code in a file named JavaClass.java; compiles the file with a command like:
javac JavaClass.java
Write a .NET C# application like the following one:
using MASES.JCBridge.C2JBridge; using System; namespace JavaClassUseExample { class TestClass : SetupJVMWrapper<TestClass> { public override string ClassPath { get { return @".\"; } } public void Execute() { var jCInstance = DynJVM.JavaClass.@new(); double a = 2; double b = 3; double c = Math.PI / 2; string hello = jCInstance.helloWorld(); double result = jCInstance.add(a, b); double sin = jCInstance.sin(c); Console.WriteLine("{0} {1} + {2} = {3} and sin({4:0.0000000}) = {5:0.00000000}", hello, a, b, result, c, sin); Console.WriteLine("Press Enter to exit"); Console.ReadLine(); } } class Program { static void Main(string[] args) { try { new TestClass().Execute(); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine("Press any key."); Console.ReadKey(); } } } }
In the same folder where Java file was saved, create a .NET project and save the above code in a file named Program.cs; then compile the project with the preferred development tool.
Executing the C# code the developer has the following output:
Hello World from Java!! 2 + 3 = 5 and sin(3,1415927) = 1,00000000