java - Eclipse JDT : How to find JDK MethodInvocation and ClassInstanceCreation

标签 java abstract-syntax-tree eclipse-jdt method-invocation

我正在使用Eclipse JDT ASTVisitor从java源文件中查找Java方法调用和类实例创建。

现在,我可以找到所有这些。但我无法判断这些方法调用和类实例创建是否来自JDK库

那么,如何获取 JDK 库方法调用(例如:InputStream.read())和类实例(例如:new String())?

<小时/>

以下是我的代码。

JdtAstUtil.java

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;

public class JdtAstUtil {
    /**
     * get compilation unit of source code
     * @param javaFilePath
     * @return CompilationUnit
     */
    public static CompilationUnit getCompilationUnit(String javaFilePath){
        byte[] input = null;
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(javaFilePath));
            input = new byte[bufferedInputStream.available()];
            bufferedInputStream.read(input);
            bufferedInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ASTParser astParser = ASTParser.newParser(AST.JLS4);
        astParser.setSource(new String(input).toCharArray());
        astParser.setKind(ASTParser.K_COMPILATION_UNIT);
        astParser.setEnvironment(null, null, null, true);
        astParser.setResolveBindings(true);
        astParser.setBindingsRecovery(true);
        astParser.setUnitName("any_name");
        CompilationUnit result = (CompilationUnit) (astParser.createAST(null));
        return result;
    }
}  

DemoVisitor.java

import org.eclipse.jdt.core.dom.*;

public class DemoVisitor extends ASTVisitor {

    @Override
    public boolean visit(MethodInvocation node) {
        System.out.println("MethodInvocation:\t" + node.toString());
        System.out.println("\tExpression: " + node.getExpression());
        Expression expression = node.getExpression();
        if(expression != null) {
            ITypeBinding  typeBinding = expression.resolveTypeBinding();
            if (typeBinding != null) {
                System.out.println("\tType: " + typeBinding.getName());
            }
        }
        System.out.println("\tName: " + node.getName());
        // System.out.println("\t" + node.resolveMethodBinding());
        return true;
    }

    public void endVisit(ClassInstanceCreation node) {
        System.out.println("ClassInstanceCreation:\t" + node.toString());
        System.out.println("\tType: " + node.getType().toString());
    }
}  

DemoVisitorTest.java

import org.eclipse.jdt.core.dom.CompilationUnit;

public class DemoVisitorTest {

    public DemoVisitorTest(String path) {
        CompilationUnit comp = JdtAstUtil.getCompilationUnit(path);
        DemoVisitor visitor = new DemoVisitor();
        comp.accept(visitor);
    }
    public static void main(String args[]) {
        DemoVisitorTest test = new DemoVisitorTest
                ("/home/luckcul/developSpace/test/test.java");
    }
}  

我使用上面的代码来解析以下test.java文件。

测试.java

package com.mtihc.minecraft.myhelppages;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;

public class HelpCommandExecutor implements CommandExecutor {

    /***
     * Copies bytes from a large (over 2GB) InputStream to an OutputStream.
     * This method uses the provided buffer, so there is no need to use a
     * BufferedInputStream.
     * @param input the InputStream to read from
    * */
    public static long copyLarge(final InputStream input,
                                 final OutputStream output, final byte[] buffer) throws IOException {
        long count = 0;
        int n;
        CommandExecutor t = new CommandExecutor(new String());
        while (EOF != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        t.test();
            count += n;
        }
        return count;
    }
}

最后,我得到了这些:

ClassInstanceCreation:  new String()
    Type: String
ClassInstanceCreation:  new CommandExecutor(new String())
    Type: CommandExecutor
MethodInvocation:   input.read(buffer)
    Expression: input
    Type: InputStream
    Name: read
MethodInvocation:   output.write(buffer,0,n)
    Expression: output
    Type: OutputStream
    Name: write
MethodInvocation:   t.test()
    Expression: t
    Type: CommandExecutor
    Name: test

在此示例中,我只想获取来自 JDK 库的 new String()、InputStream.read()、OutputStream.write()

如何修改代码来解决我的问题?

最佳答案

您可能想要使用 JDT 的 Java 模型来查找所调用方法的声明类。策略的基本(未经测试)草图:

ITypeBinding declaringType = invocation.resolveMethodBinding().getDeclaringClass();
IJavaProject javaProject = JavaCore.create(iProject); // assumes you have an IProject
IType type = javaProject.findType(declaringType.getQualifiedName());
IJavaElement root = type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
IClasspathEntry cpEntry = ((IPackageFragmentRoot) root).getRawClasspathEntry();

对于 JDK 类型,cpEntry 应为 getEntryKind() CPE_CONTAINER,其 getPath() 应为从“org.eclipse.jdt.launching.JRE_CONTAINER”开始。

关于java - Eclipse JDT : How to find JDK MethodInvocation and ClassInstanceCreation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46365993/

相关文章:

java - URL 在 "["方括号处被拆分

java - 在java中寻找最小的 float

java - 更改自动生成的主要方法的 Eclipse 模板?

Java : Import a class programmatically

java - 有没有办法在 Eclipse 中对括号进行颜色编码?

java - HibernateCallback 最适合执行 SQL/过程吗?

java - 如何使用 PrepareStatement 在 Java 中执行 INSERT SELECT INTO

java - 从注释中获取值(value)

python - 改变方程的 ast.NodeTransformer 示例

haskell - 在Haskell中选择AST表示形式