Apache NetBeans
Apache NetBeans
Latest release

Apache NetBeans 23

Download

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;
    }

}