开发环境准备

安装 Eclipse IDE for RCP and RAP Developers 版本,确保包含 PDE(Plugin Development Environment)工具。JDK 建议使用 1.8 或更高版本,与公司项目保持一致。

在 Eclipse 中新建插件项目:File → New → Other → Plug-in Project。勾选 "Generate an activator" 和 "This plug-in will make contributions to the UI",模板选择 "Hello World Command"。

核心扩展点实现

通过扩展 org.eclipse.ui.commands 定义菜单项/工具栏按钮。示例代码注册生成命令:

<extension point="org.eclipse.ui.commands">
  <command id="com.example.generateCode" 
           name="Generate Company Code"/>
</extension>

实现 org.eclipse.ui.handlers 执行逻辑:

public class CodeGeneratorHandler extends AbstractHandler {
  @Override
  public Object execute(ExecutionEvent event) {
    ISelection selection = HandlerUtil.getCurrentSelection(event);
    // 获取当前选择的Java元素
  }
}

代码模板引擎设计

创建 Velocity 模板文件存储公司规范模板:

/**
 * ${className} 符合公司 ${department} 部门开发规范
 * 创建日期: ${date}
 */
public class ${className} {
    // 公司要求的类注释模板
}

通过 JDT Core 操作AST:

CompilationUnit unit = AST.parseCompilationUnit(char[] source);
AST ast = unit.getAST();
TypeDeclaration type = ast.newTypeDeclaration();
type.setName(ast.newSimpleName("GeneratedClass"));

规范适配策略

读取公司规范配置文件(XML/JSON):

<codingRules>
  <naming prefix="CT_" suffix="_Impl"/>
  <methodLimit>20</methodLimit>
</codingRules>

实现校验器检查生成的代码:

public void validate(IType type) {
  if(type.getMethods().length > 20) {
    throw new ValidationException("方法数量超过限制");
  }
}

部署与集成

导出为可部署插件:右键项目 → Export → Deployable plug-ins and fragments。通过 p2 仓库方式分发到团队环境。

配置目标平台包含公司内部依赖:Window → Preferences → Plug-in Development → Target Platform。添加公司内部框架的OSGi bundle。

调试技巧

使用 Run → Run Configurations → Eclipse Application 启动测试运行时。通过 OSGi Console(ALT+SHIFT+F1)查看插件状态。

断点设置在模板处理关键节点:AST解析、代码生成、验证流程等阶段。使用 Display View 实时观察生成的代码结构。

Logo

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

更多推荐