首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Eclipse 插件開發實戰(四):代碼生成器核心邏輯與插件集成全流程

     編輯:Java 綜合教學

前言:從 UI 交互到業務代碼生成

前三篇確立了插件項目創建、右鍵菜單彈出等 UI 基礎。本篇聚焦核心業務——領域對象到 Form/Assembler 代碼的自動生成。為解耦插件與生成邏輯,獨立建立生成器項目,參考開源 Koala 專案思想,採用 Velocity 模板引擎實現。

核心架構設計

生成目標

  • Form:業務層 VO(數據傳輸對象)
  • Assembler:領域對象 ↔ Form 雙向轉換裝配器

關鍵技術組件

組件職責
NewFile 抽象基類 封裝文件路徑解析、包名轉換、模板加載、文件寫入通用邏輯
FormNewFile 生成 Form 類,管理字段映射、導入包、模板路徑
AssemblerNewFile 生成 Assembler 類,處理轉換邏輯模板
CURDClassLoader 自定義 URLClassLoader,掃描 Web 項目 /WEB-INF/classes 與 /WEB-INF/lib 下所有 Class/Jar,支持反射加載領域對象
CURDCoreAnalysis 核心分析引擎:遞歸掃描實體類及父類字段,通過反射提取字段名、類型,構建 EntityModel / FieldModel 元數據模型
CodeGenerator 統一入口:解析輸入路徑 → 調用分析器 → 填充 Velocity 上下文 → 驅動 Form/Assembler 生成

核心類實現細節

CURDClassLoader:動態加載項目類

private void initLoader() throws MalformedURLException {
    if ("WEB".equals(webType)) {
        String dir = webRootPath + "/web/WEB-INF/classes/";
        String libs = webRootPath + "/web/WEB-INF/lib/";
        loadeWeb(dir, libs);
    } else {
        String dir = webRootPath + "/bin";
        loadJar(dir);
    }
}

private void loadeWeb(String dir, String libs) throws MalformedURLException {
    urlList.add(new URL("file:" + dir));
    File lib = new File(libs);
    for (File jarFile : lib.listFiles()) {
        urlList.add(new URL("file:" + jarFile.getAbsolutePath()));
    }
}

// 構造時構建 URLClassLoader
URL[] urls = urlList.toArray(new URL[0]);
classloader = new URLClassLoader(urls);

CURDCoreAnalysis:反射分析實體元數據

public EntityModel analysis(String projectPath, String srcJava) throws Exception {
    classloader = CURDClassLoader.getInstance(projectPath);
    EntityModel entity = analysisField(srcJava); // 遞歸分析含父類字段
    classloader.close();
    return entity;
}

private void analysisField(Class classEntity, EntityModel entity) {
    // 收集當前類及所有父類
    List<Class> classesForAnalysis = new ArrayList<>();
    classesForAnalysis.add(classEntity);
    Class superClass = classEntity.getSuperclass();
    while (superClass != null) {
        classesForAnalysis.add(superClass);
        superClass = superClass.getSuperclass();
    }
    // 從頂層父類開始分析,確保字段順序正確
    for (int i = classesForAnalysis.size() - 1; i >= 0; i--) {
        Class clazz = classesForAnalysis.get(i);
        for (Field field : clazz.getDeclaredFields()) {
            if (Modifier.isStatic(field.getModifiers())) continue; // 跳過 static
            entity.getFields().add(new FieldModel(field.getName(), field.getType().getName()));
        }
    }
}

CodeGenerator:統一生成流程

public static void generateCode(String javaPath) throws Exception {
    // 1. 解析項目路徑與類全名
    String projectPath = javaPath.substring(0, javaPath.indexOf("/src") + 1);
    projectPath = projectPath.substring(0, projectPath.lastIndexOf("/"));
    String srcJava = javaPath.substring(javaPath.indexOf("/src") + 4)
        .replace("/", ".")
        .replace(".java", "");

    // 2. 核心分析
    EntityModel entityModel = CURDCoreAnalysis.getInstance().analysis(projectPath, srcJava);

    // 3. Velocity 上下文注入
    VelocityContext context = VelocityContextUtils.getVelocityContext();
    context.put("entity", entityModel);

    // 4. 生成 Form 與 Assembler
    FormNewFile formNewFile = createFormFile(projectPath, entityModel);
    formNewFile.process();
    AssemblerNewFile assemblerNewFile = createAssemblerFile(projectPath, entityModel);
    assemblerNewFile.process();
}

插件集成:將生成器打包為 Jar 嵌入

  1. 導出生成器項目為 generator.jar
  2. 拷貝至插件項目 lib/ 目錄並加入 Classpath
  3. 在菜單處理器 execute() 中調用:
    public Object execute(ExecutionEvent event) throws ExecutionException {
        String path = getSelectPath(); // 獲取右鍵選中的 Java 文件路徑
        if (path != null) {
            try {
                CodeGenerator.generateCode(path);
                MessageDialog.openInformation(null, "生成代碼", "生成代碼成功!!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

驗證演示

Web 項目編譯輸出路徑配置
修改編譯輸出至 web/WEB-INF/classes,確保 ClassLoader 掃描到編譯後類文件
生成代碼結果目錄結構
右鍵領域對象 → 生成代碼 → 自動產出 Form 與 Assembler 文件

源碼下載:TestPlugin.rar

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved