javac#.netexecutable-jarjava-interop

Call Java method from .Net


I've to call a java method from a C# .Net concole application.

The solution at the following link

Process myProcess = new Process();
Process.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = "java";
myProcess.StartInfo.Arguments = "-jar D:\\myjava.jar";
myProcess.Start();e

doesn't allow an usefull return value (e.g. a string object) from the jar file to the .Net console app.

Another approach could be use IKVM but the developments are over and it seems to be to old to be used in an stable enterprise solution.

How can I call a java method and geta string as result value?


Solution

  • IKVM is pretty heavyweight (not to mention discontinued) so if you can avoid it then it might be easier.

    If the Java program can produce its output on STDOUT (i.e. write to the console) then you could read that output via your Process object.

    For example:

    Process myProcess = new Process();
    myProcess.StartInfo.UseShellExecute = false;
    myProcess.StartInfo.FileName = "java";
    myProcess.StartInfo.Arguments = "-jar D:\\myjava.jar";
    myProcess.StartInfo.RedirectStandardOutput = true;
    myProcess.Start();
    var output = myProcess.StandardOutput.ReadToEnd();
    

    You may need to experiment with setting other properties on your ProcessStartInfo.