Java转UML类图实现方法

一、maven依赖
<dependency>
    <groupId>com.github.javaparser</groupId>
    <artifactId>javaparser-core</artifactId>
    <version>3.26.0</version>
</dependency>

二、解析Java文件类关系

import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;

import java.io.File;
import java.io.IOException;

public class JavaToUmlConverter {
    public static void main(String[] args) throws IOException {
        File javaFile = new File("path/to/java/file.java");
        CompilationUnit cu = JavaParser.parse(javaFile);

        for (ClassOrInterfaceDeclaration clazz : cu.findAll(ClassOrInterfaceDeclaration.class)) {
            System.out.println("Class: " + clazz.getName());
        }
    }
}

三、java转U ML

import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;

import java.io.File;
import java.io.IOException;

public class JavaToUmlConverter {
    public static void main(String[] args) throws IOException {
        File javaFile = new File("path/to/java/file.java");
        CompilationUnit cu = JavaParser.parse(javaFile);

        StringBuilder umlCode = new StringBuilder();
        umlCode.append("@startuml\n");

        for (ClassOrInterfaceDeclaration clazz : cu.findAll(ClassOrInterfaceDeclaration.class)) {
            umlCode.append("class ").append(clazz.getName()).append(" {}\n");
        }

        umlCode.append("@enduml");

        System.out.println(umlCode.toString());
    }
}

 

posted @ 2024-06-05 18:19  atom_lxh  阅读(13)  评论(0编辑  收藏  举报