Skip to content

Instantly share code, notes, and snippets.

@edwardw
Last active December 21, 2016 02:56
Show Gist options
  • Save edwardw/a04daf1af92a645aa348444d170a143d to your computer and use it in GitHub Desktop.
Save edwardw/a04daf1af92a645aa348444d170a143d to your computer and use it in GitHub Desktop.
Determine java class hierarchies programmatically
import java.io.File;
import java.util.Set;
import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;
import javax.tools.*;
import com.sun.source.tree.*;
import com.sun.source.util.*;
import static java.util.Collections.singleton;
public class ClassHierarchy {
public static void main(String... args) throws Exception {
File search_dir = new File(args[0]);
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager jfm = jc.getStandardFileManager(null, null, null);
jfm.setLocation(StandardLocation.SOURCE_PATH, singleton(search_dir.getAbsoluteFile()));
Iterable<JavaFileObject> sources = jfm.list(StandardLocation.SOURCE_PATH,
"",
singleton(JavaFileObject.Kind.SOURCE),
true);
JavaCompiler.CompilationTask task = jc.getTask(null, jfm, null, null, null, sources);
task.setProcessors(singleton(new CodeProcessor()));
task.call();
}
}
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes("*")
class CodeProcessor extends AbstractProcessor {
private final ASTVisitor visitor = new ASTVisitor();
private Trees ast;
@Override
public void init(ProcessingEnvironment pe) {
super.init(pe);
ast = Trees.instance(pe);
}
@Override
public boolean process(Set<? extends TypeElement> _annotations, RoundEnvironment env) {
for (Element e: env.getRootElements()) {
Tree node = ast.getTree(e);
node.accept(visitor, null);
}
return true;
}
}
class ASTVisitor extends SimpleTreeVisitor<Object, Trees> {
@Override
public Object visitClass(ClassTree node, Trees ast) {
System.out.println(node.getSimpleName());
System.out.println("\textends: " + node.getExtendsClause());
System.out.println("\timpls: " + node.getImplementsClause());
return super.visitClass(node, ast);
}
}
$ javac -version
javac 1.8.0_112

$ javac -cp path/to/tools.jar:. ClassHierarchy.java
$ java -cp path/to/tools.jar:. ClassHierarchy .
ClassHierarchy
        extends: null
        impls:
CodeProcessor
        extends: AbstractProcessor
        impls:
ASTVisitor
        extends: SimpleTreeVisitor<Object, Trees>
        impls:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment