Given you have the access to the source files, this should work. And apparently, I can't take full credit. CollectionGenericsTypeExctractor.java helps a lot. And man, the API is ugly!
Last active
December 21, 2016 02:56
-
-
Save edwardw/a04daf1af92a645aa348444d170a143d to your computer and use it in GitHub Desktop.
Determine java class hierarchies programmatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment