Compile Java code at runtime using C #

I know that it is possible to compile C # code at runtime using C # with CSharpCodeProvider and CodeDom.

Can Java be compiled as well? If this is not the case, is there an alternative?

I want my application to be able to compile C # and Java code.

+4
source share
3 answers

To expand on what driis and ppeterka say, there is no built-in way since Java is not a .NET language (J # was close, but no longer exists). You will need to use Process.Start to start the java compiler.

+1
source
  • You will need to install the JDK (or equivalent) in the compilation system

  • You will need to call the Java compiler

  • You will probably have to use compiled code using the Java Runtime (or equivalent)

Method A: The easiest way to use the compiler and use the compiled code is Process.Start , as stated in Cyrene's answer. This is easy if you have the necessary components.

 //add this either atusing System.Diagnostics; static void CompileJava(string javacPathName, string javaFilePathName, string commandLineOptions = "") { var startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; startInfo.FileName = javacPathName; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.Arguments = commandLineOptions + " " + javaFilePathName; try { using (var javacProcess = Process.Start(startInfo)) { javacProcess.WaitForExit(); } } catch(Exception e) { // do something eg throw a more appropriate exception } } 

Method B: If you need deeper integration, you can try your own binding method (for example, use .NET and the native Java interfaces to interact between them without calling external processes). The prerequisites are the same as in Method A. The required investments are much higher, and you should only consider this if there are certain performance indicators or other limitations that Method A cannot fulfill.

You can find the information at the links below:

From C # side: http://blogs.msdn.com/b/texblog/archive/2007/04/05/linking-native-c-into-c-applications.aspx

From the Java side: http://docs.oracle.com/javase/6/docs/technotes/guides/jni/

+2
source

This may require your specific situation, but Java is not built for this, it is built to compile at compile time, and not at run time. While Miltiadis Kokkonidis answers, it might be better to use either another language that is best suited to your problem, or use strengths for a specific situation, and then try to squeeze it so that it does not correspond to the places that it does not want to go to.

0
source

All Articles