Java Tutorial/Development/Compiler Diagnostic — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 15:30, 31 мая 2010

Compile a Java code

import java.io.IOException;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class FirstCompile {
  public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int results = compiler.run(null, null, null, "Foo.java");
    System.out.println("Success: " + (results == 0));
  }
}
// File: MyClass.java
class MyClass {
  public static void main(String args[]) {
    System.out.println("Hello, World");
  }
}





Compile a Java file with JavaCompiler

import java.io.IOException;
import java.util.Arrays;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class DiagnosticCollectorCompile {
  public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
        .getJavaFileObjectsFromStrings(Arrays.asList("Foo.java"));
    JavaCompiler.rupilationTask task = compiler.getTask(null, fileManager, diagnostics, null,
        null, compilationUnits);
    boolean success = task.call();
    fileManager.close();
    System.out.println("Success: " + success);
  }
}
// File: MyClass.java
class MyClass {
  public static void main(String args[]) {
    System.out.println("Hello, World");
  }
}





Compiling from Memory

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.Arrays;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.rupilationTask;
import javax.tools.JavaFileObject.Kind;
public class CompileSourceInMemory {
  public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);
    out.println("public class HelloWorld {");
    out.println("  public static void main(String args[]) {");
    out.println("    System.out.println(\"This is in another java file\");");    
    out.println("  }");
    out.println("}");
    out.close();
    JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());
    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
    
    boolean success = task.call();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
      System.out.println(diagnostic.getCode());
      System.out.println(diagnostic.getKind());
      System.out.println(diagnostic.getPosition());
      System.out.println(diagnostic.getStartPosition());
      System.out.println(diagnostic.getEndPosition());
      System.out.println(diagnostic.getSource());
      System.out.println(diagnostic.getMessage(null));
    }
    System.out.println("Success: " + success);
    if (success) {
      try {
        Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class })
            .invoke(null, new Object[] { null });
      } catch (ClassNotFoundException e) {
        System.err.println("Class not found: " + e);
      } catch (NoSuchMethodException e) {
        System.err.println("No such method: " + e);
      } catch (IllegalAccessException e) {
        System.err.println("Illegal access: " + e);
      } catch (InvocationTargetException e) {
        System.err.println("Invocation target: " + e);
      }
    }
  }
}
class JavaSourceFromString extends SimpleJavaFileObject {
  final String code;
  JavaSourceFromString(String name, String code) {
    super(URI.create("string:///" + name.replace(".","/") + Kind.SOURCE.extension),Kind.SOURCE);
    this.code = code;
  }
  @Override
  public CharSequence getCharContent(boolean ignoreEncodingErrors) {
    return code;
  }
}





Compiling with a DiagnosticListener

import java.io.IOException;
import java.util.Arrays;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class SecondCompile {
  public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
        .getJavaFileObjectsFromStrings(Arrays.asList("YourFile.java"));
    Iterable<String> options = Arrays.asList("-d", "classes", "-sourcepath", "src");
    JavaCompiler.rupilationTask task = compiler.getTask(null, fileManager, diagnostics, options,
        null, compilationUnits);
    boolean success = task.call();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
      System.out.println(diagnostic.getCode());
      System.out.println(diagnostic.getKind());
      System.out.println(diagnostic.getPosition());
      System.out.println(diagnostic.getStartPosition());
      System.out.println(diagnostic.getEndPosition());
      System.out.println(diagnostic.getSource());
      System.out.println(diagnostic.getMessage(null));
    }
    fileManager.close();
    System.out.println("Success: " + success);
  }
}





Diagnostic Demo

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompilerTool;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompilerTool.rupilationTask;
public class DiagnosticDemo {
  public static void main(String[] args) {
    String sourceFile = "c:/HelloWorld.Java";
    JavaCompilerTool compiler = ToolProvider.getSystemJavaCompilerTool();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager =
    compiler.getStandardFileManager(diagnostics);
    List<File> sourceFileList = new ArrayList<File>();
    sourceFileList.add(new File(sourceFile));
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
        .getJavaFileObjectsFromFiles(sourceFileList);
    CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    task.run();
    try {
      fileManager.close();
    } catch (IOException e) {
    }
    List<Diagnostic<? extends JavaFileObject>> diagnosticList = diagnostics.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticList) {
      System.out.println("Position:" + diagnostic.getStartPosition());
    }
  }
}





Java Compiler tools: how you can compile a Java source from inside a Java program

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.tools.JavaCompilerTool;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompilerTool.rupilationTask;
public class JavaCompilerDemo {
    public static void main (String[] args) {
        String sourceFile = "c:/HelloWorld.Java";
        JavaCompilerTool compiler = ToolProvider.getSystemJavaCompilerTool ();
        StandardJavaFileManager fileManager =
                compiler.getStandardFileManager (null);
        // prepare the source file(s) to compile
        List<File> sourceFileList = new ArrayList <File> ();
        sourceFileList.add (new File (sourceFile));
        Iterable<? extends JavaFileObject> compilationUnits =fileManager.getJavaFileObjectsFromFiles (sourceFileList);
        CompilationTask task = compiler.getTask (null,fileManager, null, null, null, compilationUnits);
        task.run ();
        boolean result = task.getResult ();
        if (result) {
            System.out.println ("Compilation was successful");
        } else {
            System.out.println ("Compilation failed");
        }
        try {
            fileManager.close ();
        } catch (IOException e) {
        }
    }
}
/*
 * import Java.util.Date;
public class HelloWorld {
    public static void main (String[] args) {
        Date date = new Date (1234, 11, 12);
        System.out.println ("[" + date + "] Hello World !");
    }
}
 */