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

运行离线 Python 校验:KClass/Class 互转、KFunction/KProperty 引用、createInstance 与可空性元数据

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。explore-reflection.py
explore-reflection.py216 行
"""Offline Kotlin 2.x semantic verifier for Chapter 36: Reflection."""
from dataclasses import dataclass
import json

VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"


@dataclass
class KTypeMeta:
    name: str
    is_marked_nullable: bool

    def __str__(self) -> str:
        return f"{self.name}?" if self.is_marked_nullable else self.name


def case_kclass_and_java_interop():
    class Site:
        def __init__(self, name: str, age: int):
            self.name = name
            self.age = age

    kclass_meta = {
        "simpleName": "Site",
        "qualifiedName": "com.example.Site",
        "java_name": "com.example.Site",
    }
    site = Site("Kotlin", 10)
    same_class = type(site) is Site
    round_trip_name = kclass_meta["java_name"].rsplit(".", 1)[-1]

    stdlib_ops = {"simpleName", "qualifiedName", "java"}
    reflect_lib_ops = {"memberProperties", "declaredMemberFunctions", "primaryConstructor", "call", "createInstance"}

    actual = {
        "simple_name": kclass_meta["simpleName"],
        "qualified_name": kclass_meta["qualifiedName"],
        "instance_same_kclass": same_class,
        "java_round_trip": round_trip_name,
        "requires_kotlin_reflect_for_members": "memberProperties" in reflect_lib_ops and "simpleName" in stdlib_ops,
    }
    expected = {
        "simple_name": "Site",
        "qualified_name": "com.example.Site",
        "instance_same_kclass": True,
        "java_round_trip": "Site",
        "requires_kotlin_reflect_for_members": True,
    }
    return {
        "name": "kclass_and_java_interop",
        "summary": "Verify KClass metadata, ::class.java <-> .kotlin round-trip, and stdlib vs kotlin-reflect boundary",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_kfunction_and_kproperty_refs():
    def add(a: int, b: int) -> int:
        return a + b

    class Calculator:
        def multiply(self, a: int, b: int) -> int:
            return a * b

    # KFunction2: direct invoke vs call vs callBy
    params = ("a", "b")

    def call_by(fn, mapping: dict[str, int]) -> int:
        ordered = [mapping[p] for p in params]
        return fn(*ordered)

    calc = Calculator()

    # KProperty1 / KMutableProperty1 / KProperty0
    class User:
        def __init__(self, name: str, age: int):
            self.name = name
            self.age = age

    user = User("Kotlin", 10)
    name_before = getattr(user, "name")
    age_before = getattr(user, "age")
    setattr(user, "age", 20)

    top_level_site = "mbsky.cn"
    config_version = "Kotlin 2.2"

    actual = {
        "fn_name": add.__name__,
        "fn_param_count": len(params),
        "direct_invoke": add(3, 4),
        "call_by_reordered": call_by(add, {"b": 4, "a": 3}),
        "bound_member_call": calc.multiply(5, 6),
        "kprop1_name": name_before,
        "kmprop1_age_transition": [age_before, user.age],
        "kprop0_values": [top_level_site, config_version],
    }
    expected = {
        "fn_name": "add",
        "fn_param_count": 2,
        "direct_invoke": 7,
        "call_by_reordered": 7,
        "bound_member_call": 30,
        "kprop1_name": "Kotlin",
        "kmprop1_age_transition": [10, 20],
        "kprop0_values": ["mbsky.cn", "Kotlin 2.2"],
    }
    return {
        "name": "kfunction_and_kproperty_refs",
        "summary": "Verify KFunction invoke/call/callBy, bound references, KProperty1/KMutableProperty1, and KProperty0",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_member_introspection_and_create_instance():
    class DemoSite:
        def __init__(self, name: str = "Kotlin", age: int = 10):
            self.name = name
            self.age = age

        def greet(self) -> str:
            return f"欢迎来到 {self.name}"

    class RequiredArgsSite:
        def __init__(self, name: str, url: str):
            self.name = name
            self.url = url

    inst = DemoSite("Kotlin", 10)
    sorted_props = sorted((k, v) for k, v in vars(inst).items())
    declared_fns = sorted(
        k for k, v in DemoSite.__dict__.items() if callable(v) and not k.startswith("__")
    )
    greet_res = getattr(inst, "greet")()

    # createInstance() works when all params have defaults, fails when required args exist
    created_default = DemoSite()
    no_arg_failed = False
    try:
        RequiredArgsSite()  # type: ignore[call-arg]
    except TypeError:
        no_arg_failed = True
    ctor_created = RequiredArgsSite("Kotlin", "mbsky.cn")

    actual = {
        "sorted_props": sorted_props,
        "declared_fns": declared_fns,
        "greet_call": greet_res,
        "create_instance_default_name": created_default.name,
        "create_instance_without_defaults_fails": no_arg_failed,
        "primary_ctor_call": f"{ctor_created.name} -> {ctor_created.url}",
    }
    expected = {
        "sorted_props": [("age", 10), ("name", "Kotlin")],
        "declared_fns": ["greet"],
        "greet_call": "欢迎来到 Kotlin",
        "create_instance_default_name": "Kotlin",
        "create_instance_without_defaults_fails": True,
        "primary_ctor_call": "Kotlin -> mbsky.cn",
    }
    return {
        "name": "member_introspection_and_create_instance",
        "summary": "Verify sorted memberProperties, declaredMemberFunctions lookup, createInstance, and primaryConstructor",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_kotlin_vs_java_reflection_nullability():
    profile_props = {
        "name": KTypeMeta("kotlin.String", False),
        "nickname": KTypeMeta("kotlin.String", True),
    }
    report = [
        f"{k}: {profile_props[k]},可空 = {str(profile_props[k].is_marked_nullable).lower()}"
        for k in sorted(profile_props)
    ]
    actual = {
        "nullability_report": report,
        "java_reflection_reads_kotlin_nullability_natively": False,
        "kotlin_reflection_reads_isMarkedNullable": True,
    }
    expected = {
        "nullability_report": [
            "name: kotlin.String,可空 = false",
            "nickname: kotlin.String?,可空 = true",
        ],
        "java_reflection_reads_kotlin_nullability_natively": False,
        "kotlin_reflection_reads_isMarkedNullable": True,
    }
    return {
        "name": "kotlin_vs_java_reflection_nullability",
        "summary": "Verify KType.isMarkedNullable distinguishing kotlin.String vs kotlin.String?",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_kclass_and_java_interop(),
        case_kfunction_and_kproperty_refs(),
        case_member_introspection_and_create_instance(),
        case_kotlin_vs_java_reflection_nullability(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。

入口文件:projects/kotlin-reflection-lab/explore-reflection.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-reflection.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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