0

如何使用 ASTParser 获取方法声明的 typeParameters。同样,如何获取方法调用的 typeArguments。

例如:

public void abc(String a[], String b[])
{ .. }

我想提取“ [String[], String[]]”。

谢谢。

4

1 回答 1

2

您可以执行以下操作:

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclaration;

public class Test {
    public static void main(final String args[]) {
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setSource("public class A { int i = 9;  \n int j; \n ArrayList<Integer> al = new ArrayList<Integer>();j=1000; public void test(String arg1[], String arg2[]) {}}"
                .toCharArray());

        parser.setKind(ASTParser.K_COMPILATION_UNIT);

        final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

        cu.accept(new ASTVisitor() {

            @Override
            public boolean visit(final MethodDeclaration node) {
                System.out.println("declaring method '" + node.getName() + "' that returns " + node.getReturnType2());
                List<String> parameters = new ArrayList<String>();
                for (Object parameter : node.parameters()) {
                    VariableDeclaration variableDeclaration = (VariableDeclaration) parameter;
                    String type = variableDeclaration.getStructuralProperty(SingleVariableDeclaration.TYPE_PROPERTY)
                            .toString();
                    for (int i = 0; i < variableDeclaration.getExtraDimensions(); i++) {
                        type += "[]";
                    }
                    parameters.add(type);
                }

                System.out.println(parameters);

                return true;
            }

        });
    }
}
于 2012-06-16T10:45:51.020 回答