Skip to content

Adding and Deleting Fields

Jon Schneider edited this page Nov 28, 2016 · 1 revision

Adding a field

Starting with a barebones class:

class A {
}

Adding a field looks like this:

Tr.CompilationUnit cu = parser.parse(a)
Tr.ClassDecl a = cu.getFirstClass();

cu.refactor()
	.addField(a, List.class, "list", "new ArrayList<>()")
	.addImport(java.util.ArrayList)
    .fix();

The class reference to List.class can be replaced with a fully qualified name java.util.List, and the initialization block is optional.

Support for adding generic parameters is not yet included.

The initialization block is inserted into the AST as raw source, so subsequent operations on the transformed AST will not recognize this expression as a Tr.NewClass and the ArrayList type will not be seen to be in use. This is also why it is wise to add an import on ArrayList in this case.

Deleting a field

After the add field operation, our class will look like this:

import java.util.ArrayList;
import java.util.List;

class A {
	private List list = new ArrayList<>();
}

We can effectively undo the operation with:

a.deleteField(a.findFields("java.util.List")).fix();