Table of Contents

.NET simple example

Java class use example

This is a basic example where a Java class is called from a .NET application (.NET Framework, .NET 10 or .NET 11). It assumes:

  • an installed JDK, to build the Java snippet
  • a development environment to build the .NET project
  • at runtime, the JRE/JDK location is found with the standard methods: environment variable or, on Windows, the registry

Consider the following Java code:

public class JavaClass {
    /**
     * Returns the "Hello World!!" string
     * @return "Hello World!!" string
     */
    public String helloWorld()
    {
        return "Hello World from Java!!";
    }

    /**
     * Returns the sum of two doubles
     * @param a
     * @param b
     * @return a + b
     */
    public double add(double a, double b)
    {
        return a+b;
    }

    /**
     * Returns the sine of a double
     * @param a
     * @return sin of a
     */
    public double sin(double a)
    {
        return Math.sin(a);
    }
}

Create a folder, save the code in a file named JavaClass.java and compile it:

javac JavaClass.java

Write a .NET C# application like the following one:

using MASES.JCOBridge.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 as the Java file, create a .NET project, save the code in a file named Program.cs and build the project with your preferred tool.

Running the C# code gives the following output:

Hello World from Java!! 2 + 3 = 5 and sin(3,1415927) = 1,00000000