JavaHT GetIntoJavacContext

How do I Get into the Javac Context for a File?

First of all, think about what are you trying to do. There are different ways to enter the javac context for different usecases. You may go and consult Registering/Running tasks first. Then if you decide that this is not the way you may continue reading here.

Find answers to these questions:

  1. When the code is supposed to run
    1. On explicit user action, like when user invokes an action through menu, or when the user invokes the code completion.
    2. "When the file is parsed by the infrastructure" - like the coloring, editor hints, etc.
  2. What is the scope of the code
    1. one file - usually the one visible in the editor - like coloring, code completion, editor hints
    2. many files (eg. whole project) - like find usages
  3. Does the code require Trees?
  4. Will the code make any modifications into the source code (through the TreeMaker API)?

Please note that not all combinations of answers to the above questions make sense.

In all cases, you will need to create a CancellableTask, which will do the work.

Read-only access, one file Read-only access, more files Write access, one file Write access, more files
Trees, on user action I II III IV
no trees, on user action V V x (no write access without trees) x (no write access without trees)
Trees, automatically VI x x x
no Trees, automatically x x x x


I.: use JavaSource.forFileObject(/given file object/).runUserActionTask(CancellableTask<CompilationController>). Learn more on CompilationController usage ?below?.

II.: use JavaSource.create(ClasspathInfo, FileObject...).runUserActionTask(CancellableTask<CompilationController>). Learn more on CompilationController usage ?below?. Please see javadoc for the JavaSource.create method for more detailed information on how this works.

III.: use JavaSource.forFileObject(/given file object/).runModificationTask(CancellableTask<WorkingCopy>). Learn more on WorkingCopy usage ?below?. The runModificationTask method returns ModificationResult, which represents "textual" diff for changes the CancellableTask did. To commit these changes, perform ModificationResult.commit().

IV.: use JavaSource.create(ClasspathInfo, FileObject...).runModificationTask(CancellableTask<WorkingCopy>). Learn more on WorkingCopy usage ?below?. The runModificationTask method returns ModificationResult, which represents "textual" diff for changes the CancellableTask did. To commit these changes, perform ModificationResult.commit(). Please see javadoc for the JavaSource.create method for more detailed information on how this works.

V.: use JavaSource.create(ClasspathInfo)

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo