蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Eclipse Java 接口多继承骨架、顶层修饰符规则与循环继承检测离线核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-create-java-interface.py
explore-create-java-interface.py140 行
"""Offline Eclipse New Java Interface wizard skeleton & inheritance verifier for Ch12 (create-java-interface)."""
import json
import re
import tempfile
from pathlib import Path

VERSION = "CPython 3.12.14 offline Eclipse Java-interface wizard verifier (desktop Eclipse SWT GUI absent)"

IFACE_NAME_RE = re.compile(r"^[A-Z][A-Za-z0-9_$]*$")


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


def validate_top_level_interface(name, modifiers):
    if not IFACE_NAME_RE.match(name):
        return False, "invalid_name"
    illegal = set(modifiers) - {"public"}
    if illegal:
        return False, "illegal_top_level_modifier"
    return True, "ok"


def has_inheritance_cycle(graph):
    visited = {}

    def dfs(node):
        state = visited.get(node, 0)
        if state == 1:
            return True
        if state == 2:
            return False
        visited[node] = 1
        for parent in graph.get(node, ()):
            if dfs(parent):
                return True
        visited[node] = 2
        return False

    return any(dfs(n) for n in graph)


def generate_interface(package_name, iface_name, extended=(), include_comments=True):
    lines = [f"package {package_name};", ""]
    if include_comments:
        lines.extend(["/**", f" * Interface contract for {iface_name}.", " */"])
    decl = f"public interface {iface_name}"
    if extended:
        decl += " extends " + ", ".join(extended)
    lines.append(decl + " {")
    lines.append("}")
    return "\n".join(lines) + "\n"


def main():
    cases = []

    # Case 1: Java interface skeleton supporting multiple extended super-interfaces & comments
    code = generate_interface(
        "com.mbsky.contract",
        "ExportableOrder",
        extended=("Serializable", "Comparable<ExportableOrder>"),
        include_comments=True,
    )
    cases.append(
        check(
            "interface_skeleton_multi_extends",
            "Generate New Java Interface skeleton with package, multiple super-interfaces, and Javadoc comments",
            {
                "has_package": True,
                "has_multi_extends": True,
                "has_javadoc": True,
            },
            {
                "has_package": "package com.mbsky.contract;" in code,
                "has_multi_extends": "public interface ExportableOrder extends Serializable, Comparable<ExportableOrder> {" in code,
                "has_javadoc": "Interface contract for ExportableOrder." in code,
            },
        )
    )

    # Case 2: Top-level interface naming & modifier validation
    cases.append(
        check(
            "interface_modifier_and_naming_validation",
            "Verify top-level interface allows public or package-private only and rejects final/private",
            {
                "public_ok": (True, "ok"),
                "package_private_ok": (True, "ok"),
                "final_rejected": (False, "illegal_top_level_modifier"),
                "private_rejected": (False, "illegal_top_level_modifier"),
            },
            {
                "public_ok": validate_top_level_interface("Auditable", ("public",)),
                "package_private_ok": validate_top_level_interface("InternalHook", ()),
                "final_rejected": validate_top_level_interface("BadFinal", ("public", "final")),
                "private_rejected": validate_top_level_interface("BadPrivate", ("private",)),
            },
        )
    )

    # Case 3: File path placement & cycle detection in extended interface hierarchy
    with tempfile.TemporaryDirectory() as tmp:
        pkg = "com.mbsky.contract"
        path = Path(tmp) / "src" / Path(*pkg.split(".")) / "ExportableOrder.java"
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(code, encoding="utf-8")
        rel_path = path.relative_to(Path(tmp)).as_posix()
    acyclic_graph = {"ExportableOrder": ["Serializable", "Comparable"], "Serializable": [], "Comparable": []}
    cyclic_graph = {"A": ["B"], "B": ["A"]}
    cases.append(
        check(
            "interface_file_location_and_hierarchy",
            "Verify interface file placement under Source Folder/Package and detect circular interface inheritance",
            {
                "relative_path": "src/com/mbsky/contract/ExportableOrder.java",
                "acyclic_ok": True,
                "cycle_detected": True,
            },
            {
                "relative_path": rel_path,
                "acyclic_ok": not has_inheritance_cycle(acyclic_graph),
                "cycle_detected": has_inheritance_cycle(cyclic_graph),
            },
        )
    )

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


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/eclipse-create-java-interface-lab/explore-create-java-interface.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-create-java-interface.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Eclipse

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

下载课程关联工程包:Eclipse

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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