简体   繁体   中英

Compile java code in run time using C#

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

Is it possible to compile also Java? If it isn't, is there any alternative?

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

  • You will need to have JDK (or equivalent installed) on the system performing the compilation

  • You will need to invoke the Java compiler

  • You will presumably need to use the compiled code using the Java Runtime (or equivalent)

Method A: The easiest way to both use the compiler and use the compiled code would be trough Process.Start as mentioned in Kieren's answer. This is easy provided 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 e.g. throw a more appropriate exception
   }

}

Method B: If you require deeper integration, you could try the native linking method (ie use .NET and the Java native interfaces for the two to interoperate without invoking external processes). The pre-requisites are the same as with Method A. The investment required is much higher and you should only consider this if there are specific performance or other constraints Method A cannot meet.

You can find some information by following the links below:

From the 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/

To expand on what driis and ppeterka are saying, there's no built-in way since Java isn't a .NET language (J# was close but doesn't exist anymore). You'd need to use Process.Start to fire up the java compiler.

Your specific situation may require it, but Java isn't built for this, it is built to be compiled at compile time, not at runtime. While Miltiadis Kokkonidis's answer works, it's probably best to either use a different language that fits your problem better, or use the languages strengths for the situation at hand, rather then try to squeeze it to fit places it doesn't want to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM