Skip to content

Has Type and Has Import

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

Rewrite provides a shortcut to signal the presence of a certain type or import in a source file. This can be used to generate coarse statistics on how often a type appears in a set of projects.

Here is a sample class hierarchy:

import java.util.List;
import java.util.Set;
public class A {
	private List l;
	public void addToList(Set<?> s) {}
}

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

Tr.CompilationUnit cu = parser.parse(Arrays.asList(a)).get(0);

We can check for the presence of List and Set with:

cu.hasType(List.class);                 // 1
cu.getFirstClass().hasType(List.class); // 2
cu.hasType("java.util.Set");            // 3
  1. Compilation unit wide check
  2. Check only the first class for the type
  3. Use a fully qualified name to check

Notice that it doesn't matter where the type occurs in the source code. It could be in a variable declaration, a method parameter or return type, a type parameterization, etc.

Similarly, we can check for an import with:

cu.hasImport(List.class);
cu.hasImport("java.util.List");
Clone this wiki locally