Get to super declaration using Java's compiler API

83 Views Asked by At

Say I am writing annotation processor or compiler plugin, how can I get form com.sun.source.tree.MethodTree(/JCTree.JCMethodDecl) or Symbol.MethodSymbol to their "super" (if exists), e.g. if I try to compile

class A {
     public void foo() {}
}
class B extends A {
     @Override public void foo() {}
}

I want to do something like:

public class printSuper extends ...
        implements TaskListener {
    ...
    @Override
    public void finished(TaskEvent taskEvt) {
        if (taskEvt.getKind() != TaskEvent.Kind.ANALYZE) {
            return;
        }
        taskEvt.getCompilationUnit().accept(new TreeScanner<Void, Void>() {
            @Override
            public Void visitMethod(MethodTree methodDecl, Void v) {
                var zuper = magicToGetSuperDecl(methodDecl);
                // for A.foo > null/exception/some equivalent
                // for B.foo > A.foo
            }
        }, null);
    }
}

I tried to use the TreePath of methodDecl, but the best I got from there is the javax.lang.model.element.Element of the class of the method, I tried to use trees.getPath(zuperElement) I sometimes get null.

Also, from trees.getPath(zuperElement).getLeaf() I can get to list of methods the super class has, but I couldn't find a good way to get the specific method I from the super class.

0

There are 0 best solutions below