4

I was trying to create a class to compile some .java that I'll create at runtime, but I can't get this to work properly.

Here's my code

    File bin = new File(args[args.length-1]);

    System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.7.0_60");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    StandardJavaFileManager standardJavaFileManager = compiler.getStandardFileManager(null, null, null);

    try {
        standardJavaFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(bin));
    } catch (IOException e) {
        System.err.println("Invalid bin directory");
        e.printStackTrace();
    }

    List<String> options = new ArrayList<String>();

    options.add("-Xlint:unchecked");
    options.add("-classpath");
    options.add("e:\\ParentProject.jar");

    System.out.println(options);

    CompilationTask compilationTask = compiler.getTask(null, standardJavaFileManager, null, options, null, standardJavaFileManager.getJavaFileObjectsFromFiles(archives));

    compilationTask.call();

I'm trying to compile a Son.java that extends a class that is in the ParentProject.jar, but it doesn't work, even using the "-classpath" flag. However, if I add the jar to the build path of the compiler project, it works (and it doesn't need the classpath flag). Is this the normal behaviour ?

And that leads to another problem. When I try to use this piece of code in a project that is running on a Tomcat server, even with the jars in WEB-INF/lib, I can't get it to work.

1 Answers1

7

You can add the JAR to your class path like so:

standardJavaFileManager.setLocation(
    StandardLocation.CLASS_PATH, 
    Arrays.asList( new File ( "path/to/ParentProject.jar" ) )
);
Gunnar
  • 18,095
  • 1
  • 53
  • 73