javajava-compiler-api

JavaCompiler with dependent class


I'm using JavaCompiler to compile a class. I have jar dependency, where I used to give it in class path, I have a class (class1) file in the same directly, which is a dependent for another class (class2).

Simply

Class1.class Class2.java

I want to compile Class2.java, in Class2 have a code like

Class1.sayHi();

When I compile it its saying

error: cannot find symbol

How can I include Class1.class while compiling Class2

My compiler code

String fileToCompile = classFile;
System.setProperty("java.home", RuntimeCompiler.getJDKPath());
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationSource =
     fileManager.getJavaFileObjects(fileToCompile);
List<String> optionList = new ArrayList<String>();
optionList.addAll(Arrays.asList("-classpath",dynamicClassPath));
try{
    compiler.getTask(null, null, null, optionList, null, compilationSource).call();
    return true;
}catch (Exception e) {
    return false;
}

Solution

  • The class path for a particular compiled class can be given as

    -classpath "full_folder_Path_Till_Package"
    

    Ex:

    dynamicClassPath = "C:/work/sample1/core" 
    

    in core directory you will have package folder "com" inside that dependant class.