Forum Stats

  • 3,728,152 Users
  • 2,245,559 Discussions
  • 7,853,355 Comments

Discussions

Java 8 apt tool replacement for run time annotation processing ?

alinaqvi90
alinaqvi90 Member Posts: 1
edited March 2015 in Java 8 Questions

Hi

We have a legacy app which after starting up process's a number of client code java files. For e.g. the client could put abc.java in a specific folder and it would be picked up by our app and compiled and embedded within.

Our apps ships with a JRE and not a JDK and in the classpath we also have tools.jar.

From our app we compile the abc.java with the command: com.sun.tools.javac.Main.compile(file);

Then next step is that we do some annotation processing with the apt tool e.g.

args[0] = "-nocompile";

args[1]=abc.java

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            int aptReturnCode = com.sun.tools.apt.Main.process(processor, new PrintWriter(baos), fl); //where processor is the custom annotation processor.

With java-8 we have found that oracle have made the apt tool defunct so instead of using the apt tool we are supposed to use the java compiler for the same task. So I came up with code below which needed some reworking of the annotation processor but the problem is that ToolProvider.getSystemJavaCompiler() always returns null. Is there any way that I could do this annotation processing or load the java compiler with just the tools.jar in the class path without using a jdk ?

ArrayList<String> customClasses = new ArrayList<String>();

ArrayList<String> arguments = new ArrayList<String>();//arguments for the java compiler

arguments.add( "-proc:only" ); // only do annotations processing and do not compile the source code.

customClasses.add("full path/abc.java");


JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // always returns null

ByteArrayOutputStream baos = new ByteArrayOutputStream();

      

DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

  StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

  Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(customClasses);

  JavaCompiler.CompilationTask task =

  compiler.getTask(new PrintWriter(baos), fileManager, diagnostics, arguments, null, compilationUnits);

  ArrayList<Processor> processors = new ArrayList<Processor>();

  processors.add( new MyCustomProcessor() );

  task.setProcessors( processors );

  boolean success = task.call();

Many Thanks

Sign In or Register to comment.