ASTParser方法声明类型Paramaters

时间:2012-06-16 10:02:13

标签: java

如何使用ASTParser获取方法声明的typeParameters。 类似地,如何获取methodInvocations的typeArguments。

例如:

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

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

感谢。

1 个答案:

答案 0 :(得分: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;
            }

        });
    }
}