package org.work.utlis;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Java 实体类解析工具
 * 支持解析字段类型、名称和注释
 */
public class JavaEntityFieldParser {

    private static final Pattern FIELD_PATTERN = Pattern.compile(
            // 捕获类似:private String name;  private Long id;
            "(?m)^[ \\t]*(private|protected|public)[ \\t]+([\\w<>.,\\[\\]]+)[ \\t]+([a-zA-Z0-9_]+)[ \\t]*;"
    );

    public static class FieldInfo {
        public String type;
        public String name;
        public String comment;

        @Override
        public String toString() {
            return String.format("字段名: %-25s 类型: %-20s 注释: %s", name, type, comment == null ? "" : comment);
        }
    }

    public static List<FieldInfo> parse(File javaFile) throws IOException {
        String content = readFile(javaFile);
        return parse(content);
    }

    public static List<FieldInfo> parse(String content) throws IOException {
        List<FieldInfo> result = new ArrayList<>();

//        String content = new String(javaFileToBytes(javaFile), StandardCharsets.UTF_8);


        // 统一注释格式(去除多行注释换行符)
        content = content.replaceAll("\\r", "");

        // 分行解析
        String[] lines = content.split("\\n");

        // 缓存上方注释
        StringBuilder lastComment = new StringBuilder();

        for (int i = 0; i < lines.length; i++) {
            String line = lines[i].trim();

            // 1️⃣ 处理注释(支持三种格式)
            if (line.startsWith("//")) {
                lastComment.append(line.substring(2).trim()).append(" ");
                continue;
            }

            if (line.startsWith("/*")) {
                StringBuilder multiLineComment = new StringBuilder();
                multiLineComment.append(line);
                while (!line.endsWith("*/") && i + 1 < lines.length) {
                    line = lines[++i].trim();
                    multiLineComment.append("\n").append(line);
                }
                // 提取注释内容
                String commentText = multiLineComment.toString()
                        .replaceAll("/\\*+|\\*+/", "")
                        .replaceAll("\\*", "")
                        .trim();
                lastComment.append(commentText).append(" ");
                continue;
            }

            // 2️⃣ 检测字段
            Matcher matcher = FIELD_PATTERN.matcher(line);
            if (matcher.find()) {
                FieldInfo field = new FieldInfo();
                field.type = matcher.group(2);
                field.name = matcher.group(3);
                field.comment = lastComment.toString().trim();
                result.add(field);
                lastComment.setLength(0); // 清空注释缓存
            }
        }

        return result;
    }

    public static String readFile(File file) throws IOException {
        StringBuilder content = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append(System.lineSeparator());
            }
        }

        return content.toString();
    }

    public static String parseFile(File file) throws IOException {
        StringBuilder sb = new StringBuilder();

        List<FieldInfo> fields = parse(file);
        for (FieldInfo f : fields) {
            sb.append(f.name).append(" ").append(f.type).append(" ").append(f.comment).append("\n");
            System.out.println(f);
        }
        return sb.toString();
    }


    public static void main(String[] args) throws Exception {
        File file = new File("D:\\01code\\01work_java\\gaoyi\\epiboly\\src\\main\\java\\com\\ruoyi\\epiboly\\entity\\YjMunicipalPipeline.java"); // 修改为你的文件路径
        List<FieldInfo> fields = parse(file);
        String fieldsStr = parseFile(file);

        System.out.println("======= 解析结果 =======");
        for (FieldInfo f : fields) {
            System.out.println(f);
        }
    }
}

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐