Using a Visitor to extract Java methods that have a specific annotation

37 views
Skip to first unread message

Richard Lewis

unread,
Aug 10, 2015, 9:14:05 PM8/10/15
to antlr-di...@googlegroups.com
I'm building a JNI interface for an Excel add-in that extracts methods and method arguments from a JAVA source file only if there is a specific annotation on that method. Later I will use StringTemplate to generate the XLL C++ wrapper functions.  I'm using the antlr4 java grammar and a Visitor since I don't need to parse methods that do not have this annotation. What I've done works, I'm wondering if there is a simpler way to accomplish the same thing.  Essentially if a classBodyDeclaration has an @XLFunction annotation I parse the rest of the tree otherwise I ignore it. 

       @Override

       public JavaClass visitClassBodyDeclaration(JavaParser.ClassBodyDeclarationContext ctx)

       {

            String xpath = "//annotationName/qualifiedName/*"; // get all annotations

            for (ParseTree t : XPath.findAll(ctx, xpath, parser) ) {

                if ( t instanceof TerminalNode) {

                                     if ("XLFunction".equals(((TerminalNode)t).getText()))

                        return visitChildren(ctx);

                }

            }


            return cls;

       }


I have tried: "String xpath = //annotationName/qualifiedName/'XLFunction'" but it returns an exception. 

On return JavaClass contains the className, methods that have the XLFunction annotation and a list of arguments. I've attached code for reference. 

One bug I haven't figured out yet is that 

JavaClass cls = visitor.visit(tree);


returns null so I have to call explicitly:
visitor.getJavaClass();


JavaClassVisitor.java
JavaClass.java
JavaMethod.java
JavaArgument.java

Eric Vergnaud

unread,
Aug 14, 2015, 7:35:22 AM8/14/15
to antlr-discussion
Hi,
by curiosity, why don't you introspect the compiled java classes?
Eric

Richard Lewis

unread,
Aug 14, 2015, 2:19:58 PM8/14/15
to antlr-discussion
Which is now what I'm doing. I've given up and I'm using the javadoc utility to generate the source output via extending Doclet and using StringTemplate.... much easier. 
Reply all
Reply to author
Forward
0 new messages