Apache NetBeans
Apache NetBeans
Latest release

Apache NetBeans 23

Download

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

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

  2. 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.

  3. 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().

  4. 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.

  5. use JavaSource.create(ClasspathInfo)