蓝色天空.知识 · 实践 · 创造
我的收藏
Eclipse 教程目录 35章
Eclipse / LEARN BY DOING

Eclipse 重构菜单

介绍 Eclipse 重构(Refactor)功能如何自动追踪依赖并安全修改类名,说明三种打开重构菜单的方式以及 Rename 重命名预览与确认执行步骤。

学完这一章,你能够

  • 介绍 Eclipse 重构(Refactor)功能如何自动追踪依赖并安全修改类名,说明三种打开重构菜单的方式以及 Rename 重命名预览与确认执行步骤。

为什么使用重构及三种打开入口

在项目持续演进中,修改类名、方法名或包结构是高频需求。如果手工逐个查找替换,一旦有多个类依赖目标类,不仅耗费时间还极易遗漏或误改字符串字面量。Eclipse 内置的重构(Refactor)工具能够自动分析项目内的全部语义依赖关系并同步更新引用,大幅提升修改效率与安全性。

打开重构菜单主要有三种方式:在 `Package Explorer` 视图中右键目标 Java 元素(如类、包、文件)并选择 `Refactor`;在 Java 编辑器中右键光标处的 Java 元素并选择 `Refactor`;或者在 `Package Explorer`(或编辑器)中选中目标元素后直接按下快捷键 `Shift + Alt + T` 唤出快速重构弹窗。

重命名(Rename)类的完整操作流程

以在 Java 编辑器中重命名 `HelloWorld` 类为例,先选中类名 `HelloWorld` 并打开 `Refactor` 菜单。

选择 `Rename`(快捷键 `Alt + Shift + R`)后,编辑器会进入就地重命名或弹窗提示状态,输入新的类名并按下回车键提交。

确认新名称后,若涉及跨文件依赖或文件名同步变更,Eclipse 会弹出变更清单对话框,列出即将被同步修改的关联类与风险提示;核对无误后点击 `Continue`(或 `Finish`)按钮即可一次性完成全部重构。本站离线实验脚本已对类重命名跨文件引用传播、字面量保护及提取方法撤销安全完成校验。

运行 Eclipse 类重命名依赖传播、字面量隔离与提取方法撤销离线核验

含完整源码 · 144 行
展开查看收起
python
"""Offline Eclipse Refactoring (Rename dependency update & Extract Method) verifier for Ch28 (refactoring)."""
import json
import re

VERSION = "CPython 3.12.14 offline Eclipse JDT Refactoring verifier (desktop SWT IDE absent)"


def check(name, summary, expected, actual):
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def rename_java_type(files, old_name, new_name):
    token_re = re.compile(rf"\b{re.escape(old_name)}\b")
    updated = {}
    affected = []
    for fname, content in files.items():
        # Preserve quoted strings while replacing identifier tokens
        parts = re.split(r'("[^"]*")', content)
        new_parts = []
        changed = False
        for idx, part in enumerate(parts):
            if idx % 2 == 1:
                new_parts.append(part)
            else:
                replaced = token_re.sub(new_name, part)
                if replaced != part:
                    changed = True
                new_parts.append(replaced)
        new_fname = fname.replace(f"{old_name}.java", f"{new_name}.java")
        if changed or new_fname != fname:
            affected.append(fname)
        updated[new_fname] = "".join(new_parts)
    return updated, sorted(affected)


def main():
    cases = []

    # Case 1: Refactor entry points and preview of affected classes before clicking Continue
    entries = [
        "Package Explorer > Right-click > Refactor",
        "Java Editor > Right-click > Refactor",
        "Shift+Alt+T",
    ]
    workspace = {
        "HelloWorld.java": (
            "public class HelloWorld {\n"
            "    public HelloWorld() {}\n"
            "    public String label() { return \"HelloWorld literal\"; }\n"
            "}\n"
        ),
        "AppRunner.java": (
            "public class AppRunner {\n"
            "    public static void main(String[] args) {\n"
            "        HelloWorld hw = new HelloWorld();\n"
            "        System.out.println(hw.label());\n"
            "    }\n"
            "}\n"
        ),
        "Util.java": "public class Util { static int one() { return 1; } }\n",
    }
    refactored, affected = rename_java_type(workspace, "HelloWorld", "GreetingApp")

    cases.append(
        check(
            "refactor_menu_entry_and_rename_preview",
            "Verify Refactor triggers (including Shift+Alt+T) and preview list of impacted classes before Continue",
            {
                "entry_count": 3,
                "shortcut": "Shift+Alt+T",
                "preview_affected_files": ["AppRunner.java", "HelloWorld.java"],
            },
            {
                "entry_count": len(entries),
                "shortcut": entries[2],
                "preview_affected_files": affected,
            },
        )
    )

    # Case 2: Rename propagates to class, constructor, file name, and callers while preserving string literals
    cases.append(
        check(
            "rename_class_dependency_propagation",
            "Verify Rename updates file name, class/constructor, and dependent callers without corrupting string literals",
            {
                "new_file_exists": True,
                "old_file_removed": True,
                "caller_updated": True,
                "string_literal_preserved": True,
            },
            {
                "new_file_exists": "GreetingApp.java" in refactored,
                "old_file_removed": "HelloWorld.java" not in refactored,
                "caller_updated": "GreetingApp hw = new GreetingApp();" in refactored["AppRunner.java"],
                "string_literal_preserved": '"HelloWorld literal"' in refactored["GreetingApp.java"],
            },
        )
    )

    # Case 3: Extract Method and atomic Undo rollback
    original_code = (
        "int subtotal = price * qty;\n"
        "int tax = subtotal * 10 / 100;\n"
        "int total = subtotal + tax;\n"
    )
    extracted_code = (
        "int total = calcTotal(price, qty);\n"
        "// extracted: int calcTotal(int price, int qty)\n"
    )
    history = [original_code]
    current = extracted_code
    history.append(current)
    # Undo refactoring (Alt+Shift+Z)
    history.pop()
    restored = history[-1]

    cases.append(
        check(
            "extract_method_and_undo_safety",
            "Verify Extract Method produces helper call and Refactor Undo restores original source cleanly",
            {
                "extracted_has_helper": True,
                "undo_restores_exact_original": True,
            },
            {
                "extracted_has_helper": "calcTotal(price, qty)" in extracted_code,
                "undo_restores_exact_original": restored == original_code,
            },
        )
    )

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
验证 `Shift + Alt + T` 重构入口、重命名 `HelloWorld` 为 `GreetingApp` 时同步更新文件名与调用方且不误改字符串字面量,以及重构撤销恢复原代码。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2259.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Eclipse

课程关联工程包(登记关联35章) · 含当前章节或实例 · mbskycom202612a2259.zip

下载课程关联工程包:Eclipse

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2284.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

Eclipse 重构基于 Java 语法与依赖图工作,会自动重命名对应的 `.java` 文件、构造器及全工程所有类型引用,并在执行前预览受影响类,同时避免误替换注释或普通字符串中的同名文本。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习