JavaHT Modification

How can I programmatically modify a Java source file?

Most modifications are done through the API. Direct document changes are not recommended. Editing source through the API has many advantages, for instance it respects formatting settings.

This part will show you typical steps to make a modification to your source. There can be found different usecases, but this is the most common:

  • Find the JavaSource you want to work with,
  • create a task that contains code for source modification,
  • post the task to the JavaSource and commit the changes at the end.

TODO: link to example, describe what the example does.

Find the JavaSource

There are more ways to do it. For our demonstration, we use a straightforward solution, often used in tests. We omit the details of getting fileObject and we expect successful behaviour of called methods.

    File tutorialFile = getFile(getSourceDir(), "/org/netbeans/test/codegen/Tutorial1.java");
    JavaSource tutorialSource = JavaSource.forFileObject(FileUtil.toFileObject(tutorialFile));

The JavaSource represents the file Tutorial1.java in package org.netbeans.test.codegen.

Create a 'modify' task

Task is a parameterized interface with type parameter WorkingCopy. This type is requested in the next step. This next code snippet shows how to create an anonymous Task:

    Task task = new Task<WorkingCopy>() {
        ...
    }

The interface contains run method that contains code for modifying our javaSource.

    Task task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws Exception {
            ... our modification code
        }

    };

The run method contains all staff describing modification and we will dive in to the details later.

Post the task to process and commit the changes

Because we want to modify the source, we have to use runModificationTask (see its javadoc). At the end, we have to commit changes to propagate all the work to the source file - our Tutorial1.java file. This can fail, so ensure you correctly handle exceptions. The method runModificationTask() returns the modification result. This class contains all the prepared changes which haven't been propagated yet. This is good especially when someone wants to review the details of modification and decide about propagating changes to the source on the basis of result. For our demonstration, we will omit it. When result is collected, we have to call the commit() method to propagate the changes to the source code:

    ModificationResult result = tutorialSource.runModificationTask(task);
    result.commit();
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