java AST 抽象语法树-JavaParser 实际使用 | Echo Blog ---- 引子,里边没太多东西

简单使用

maven 引入

  [xml]

1
2
3
4
5
6
7
8
9
10
11

`<dependency>

<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-symbol-solver-core</artifactId>
<version>3.15.21</version>

</dependency>

<dependency>

<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>3.15.21</version>

</dependency>`

ps: 需要设置 jdk 级别为 1.8

测试代码

  • 测试类

  [java]

1
2
3
4
5
6
7
8
9

`package com.github.houbb;

public class Main {

public static void main(String[] args) {
    System.out.println("main");
}

}`

  • 输出方法名称

  [java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

`package com.github.houbb;

import com.github.javaparser.JavaParser;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import jdk.internal.org.objectweb.asm.MethodVisitor;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class MainMethodAccess {

public static void main(String[] args) throws FileNotFoundException {
    // creates an input stream for the file to be parsed
    FileInputStream in = new FileInputStream("D:\\github_other\\javaparser-maven-sample\\src\\main\\java\\com\\github\\houbb\\Main.java");

    CompilationUnit cu = StaticJavaParser.parse(in);

    // visit and print the methods names
    new MethodVisitor().visit(cu, null);
}

/**
 * Simple visitor implementation for visiting MethodDeclaration nodes.
 */
private static class MethodVisitor extends VoidVisitorAdapter {
    @Override
    public void visit(MethodDeclaration n, Object arg) {
        // here you can access the attributes of the method.
        // this method will be called for all methods in this
        // CompilationUnit, including inner class methods
        System.out.println(n.getName());
    }
}

}`

执行结果

  [plaintext]

1

main

改变方法

拓展阅读

AST

jdt

ASM

java assist

cglib

java 源码

java poet

参考资料

JavaParser:Java代码生成

javaparser 使用

JavaParser 使用指南

使用JavaParser进行java源码解析


原网址: 访问
创建于: 2021-12-28 20:10:38
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论