Skip to content

JavaHT_GetAllMembers

Antonio Vieiro edited this page Jan 25, 2018 · 1 revision

JavaHT_GetAllMembers

How do I Get All Methods/Fields/Constructors of a Class?

  • First, you need to be in a Javac context, see previous section for more information.

  • Then, you need to find javax.lang.model.element.TypeElement you want to analyze. See com.sun.source.tree.Trees.getElement(TreePath) and javax.lang.model.util.Elements.getTypeElement(String). You can get Trees and Elements from org.netbeans.api.java.source.CompilationInfo.

  • Finally, use Element.getEnclosedElements() to find out the elements enclosed by the class - for classes, this returns all members (methods, fields and inner classes) of the class. You can then use ElementFilter to filter out specific kind of member: methods, constructors, fields and inner classes.

Example:

protected void performAction(Node[] activatedNodes) {
    DataObject dataObject = (DataObject) activatedNodes[0].getLookup().lookup(DataObject.class);
    JavaSource js = JavaSource.forFileObject(dataObject.getPrimaryFile());

    try {
        js.runUserActionTask(new Task<CompilationController>() {
            public void run(CompilationController parameter) throws IOException {
                parameter.toPhase(Phase.ELEMENTS_RESOLVED);
                new MemberVisitor(parameter).scan(parameter.getCompilationUnit(), null);
            }
        }, true);
    }
    catch (IOException e) {
        Logger.getLogger("global").log(Level.SEVERE, e.getMessage(), e);
    }
}

private static class MemberVisitor extends TreePathScanner<Void, Void> {

    private CompilationInfo info;

    public MemberVisitor(CompilationInfo info) {
        this.info = info;
    }

    @Override
    public Void visitClass(ClassTree t, Void v) {
        Element el = info.getTrees().getElement(getCurrentPath());


        if (el == null) {
            System.err.println("Cannot resolve class!");
        }
        else {
            TypeElement te = (TypeElement) el;
            System.err.println("Resolved class: " + te.getQualifiedName().toString());
            //XXX: only as an example, uses toString on element, which should be used only for debugging
            System.err.println("enclosed methods: " + ElementFilter.methodsIn(te.getEnclosedElements()));
            System.err.println("enclosed types: " + ElementFilter.typesIn(te.getEnclosedElements()));
        }
        return null;
    }

}

Apache Migration Information

The content in this page was kindly donated by Oracle Corp. to the Apache Software Foundation.

This page was exported from http://wiki.netbeans.org/JavaHT GetAllMembers , that was last modified by NetBeans user Javydreamercsw on 2012-07-10T14:37:39Z.

NOTE: This document was automatically converted to the AsciiDoc format on 2018-01-26, and needs to be reviewed.

Clone this wiki locally