Skip to content

Finding Fields

Jon Schneider edited this page Nov 22, 2016 · 2 revisions

Rewrite provides a shortcut to find fields of a certain type and locate classes that inherit fields of a type from their type hierarchy.

Here is a sample class hierarchy:

import java.util.*;
public class A {
	private List l;
}

class Base {
	protected Set s;
	private Map m;
}

First, let's parse this source file and grab its Tr.CompilationUnit.

Tr.CompilationUnit cu = parser.parse(Arrays.asList(a)).get(0);
val clazz = cu.getFirstClass(); // or cu.getClasses().get(0)

We can retrieve a list of the Tr.VariableDecls instances with type Set on class A like this:

clazz.findFields("java.util.Set");
clazz.findFields(Set.class);

All Set fields are listed, regardless of their visibility. We could narrow the list to protected fields by filtering the returned list:

class.findFields(Set.class).stream()
	.filter(f -> f.hasModifier("protected"))

It is also possible to find the matching visible (with respect to A) fields inherited from A's ttype hierarchy through:

clazz.findInheritedFields("java.util.List");
class.findInheritedFields(List.class);

Since the m field on BaseClass is private, class.findInheritedFields(Map.class) will return the empty list.

Clone this wiki locally