ReflectionClass

new ReflectionClass(object|string $objectOrClass)

类的运行时自省:读取类名、方法清单与属性清单。

C C23

C23
#include <stdio.h>

typedef struct {
    int x;
    int y;
} Point;

/* C 没有反射:字段/方法清单只能手工维护「描述表」 */
static void point_move(Point *p, int dx, int dy) {
    p->x += dx;
    p->y += dy;
}

int main(void) {
    printf("Point\n");
    printf("methods: point_move (hand-written)\n");
    printf("properties: x, y (hand-written)\n");
    return 0;
}
输出
Point
methods: point_move (hand-written)
properties: x, y (hand-written)

C++ C++26

C++26
#include <iostream>

struct Point {
    int x = 0;
    int y = 0;

    void move_by(int dx, int dy) {
        x += dx;
        y += dy;
    }
};

int main() {
    // 没有运行时反射:清单只能手工维护
    // (C++26 的 P2996 是编译期静态反射,主流编译器仍在落地)
    std::cout << "Point\n";
    std::cout << "methods: move_by (hand-written)\n";
    std::cout << "properties: x, y (hand-written)\n";
    return 0;
}
输出
Point
methods: move_by (hand-written)
properties: x, y (hand-written)

C# v11.0.100

v11.0.100
using System;
using System.Linq;
using System.Reflection;

Type t = typeof(Point); // DeclaredOnly 排除继承成员
Console.WriteLine(t.Name);
Console.WriteLine("methods: " + string.Join(", ",
    t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
     .Where(m => !m.IsSpecialName) // 过滤编译器生成的 get_X/set_X 访问器
     .Select(m => m.Name)));
Console.WriteLine("properties: " + string.Join(", ",
    t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
     .Select(p => p.Name)));

class Point
{
    public int X { get; set; } = 0;
    public int Y { get; set; } = 0;

    public void Move(int dx, int dy)
    {
        X += dx;
        Y += dy;
    }
}
输出
Point
methods: Move
properties: X, Y

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"reflect"
	"strings"
)

type Point struct {
	X int
	Y int
}

func (p Point) Move(dx, dy int) {
	p.X += dx
	p.Y += dy
}

func main() {
	// reflect 只作用于导出名;指针类型的方法集
	// 同时包含值接收者与指针接收者方法
	t := reflect.TypeOf(&Point{})
	fmt.Println(t.Elem().Name())
	var methods []string
	for i := 0; i < t.NumMethod(); i++ {
		methods = append(methods, t.Method(i).Name)
	}
	fmt.Println("methods:", strings.Join(methods, ", "))
	var fields []string
	pointType := t.Elem()
	for i := 0; i < pointType.NumField(); i++ {
		fields = append(fields, pointType.Field(i).Name)
	}
	fmt.Println("properties:", strings.Join(fields, ", "))
}
输出
Point
methods: Move
properties: X, Y

Java v27.0.1

v27.0.1
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    static class Point {
        int x = 0;
        int y = 0;

        void move(int dx, int dy) {
            x += dx;
            y += dy;
        }
    }

    public static void main(String[] args) {
        Class<Point> c = Point.class; // getDeclared 系列:仅本类声明,不限可见性
        System.out.println(c.getSimpleName());
        System.out.println("methods: " + Arrays.stream(c.getDeclaredMethods())
            .map(Method::getName).collect(Collectors.joining(", ")));
        System.out.println("properties: " + Arrays.stream(c.getDeclaredFields())
            .map(Field::getName).collect(Collectors.joining(", ")));
    }
}
输出
Point
methods: move
properties: x, y

JavaScript v26.13.1

v26.13.1
// JS 没有正式的反射 API:改用对象与原型自省
class Point {
  x = 0;
  y = 0;
  move(dx, dy) {
    this.x += dx;
    this.y += dy;
  }
}
const p = new Point();
console.log(p.constructor.name);
const methods = Object.getOwnPropertyNames(Point.prototype)
  .filter((n) => n !== "constructor");
console.log(`methods: ${methods.join(", ")}`);
console.log(`properties: ${Object.keys(p).join(", ")}`);
输出
Point
methods: move
properties: x, y

PHP v8.6.0

v8.6.0
class Point {
    public int $x = 0;
    public int $y = 0;
    public function move(int $dx, int $dy): void {
        $this->x += $dx;
        $this->y += $dy;
    }
}
// ReflectionClass 把类当数据读:类名、方法清单、属性清单
$rc = new ReflectionClass(Point::class);
echo $rc->getShortName(), "\n";
echo 'methods: ', implode(', ', array_map(
    fn ($m) => $m->getName(), $rc->getMethods()
)), "\n";
echo 'properties: ', implode(', ', array_map(
    fn ($p) => $p->getName(), $rc->getProperties()
)), "\n";
输出
Point
methods: move
properties: x, y

Python v3.15.2

v3.15.2
import inspect


class Point:
    x: int = 0
    y: int = 0

    def move(self, dx: int, dy: int) -> None:
        self.x += dx
        self.y += dy


# inspect 列出声明的函数;类注解列出声明的字段
print(Point.__name__)
print("methods:", ", ".join(
    n for n, _ in inspect.getmembers(Point, inspect.isfunction)
    if not n.startswith("__")
))
print("properties:", ", ".join(Point.__annotations__))
输出
Point
methods: move
properties: x, y

Rust v1.99.1

v1.99.1
use std::any::type_name;

struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn move_by(&mut self, dx: i32, dy: i32) {
        self.x += dx;
        self.y += dy;
    }
}

fn main() {
    // Rust 没有运行时反射:type_name 是编译期字符串,
    // 下面的方法/属性清单是手写的,并非自省所得
    println!("{}", type_name::<Point>());
    println!("methods: move_by (hand-written)");
    println!("properties: x, y (hand-written)");
}
输出
main::Point
methods: move_by (hand-written)
properties: x, y (hand-written)

TypeScript v26.13.1

v26.13.1
// TS 只在编译期提供类型元数据:同样没有运行时反射,
// 所以照旧自省 JavaScript 对象形状
class Point {
  x = 0;
  y = 0;
  move(dx: number, dy: number): void {
    this.x += dx;
    this.y += dy;
  }
}
const p = new Point();
console.log(p.constructor.name);
const methods = Object.getOwnPropertyNames(Point.prototype)
  .filter((n) => n !== "constructor");
console.log(`methods: ${methods.join(", ")}`);
console.log(`properties: ${Object.keys(p).join(", ")}`);
输出
Point
methods: move
properties: x, y

语言差异说明

反射能力光谱(本条目的核心教学点):运行时保留完整类型元数据的语言自省能力最强,没有运行时元数据的编译型语言只能编译期近似或手工维护——

PHP:ReflectionClass 是一等公民 API(示例):类名/方法/属性/修饰符/参数/注解属性全部可读,还可动态 new、调用、改可见性——框架与 IDE 跳转的底座。

C:完全无反射(示例展示手工描述表惯例);类型信息在编译后彻底消失,运行期连「这个指针指向什么类型」都无从得知。

C++:同样无运行时反射(示例);typeid().name() 名字实现相关(gcc/clang 给乱码)且不列成员;C++26 已把 P2996 编译期静态反射纳入草案,主流工具链仍在落地——方向是编译期生成而非运行时查询。

C#:typeof/GetType + System.Reflection(示例)能力与 Java 同级:方法/属性/构造器/Attribute 全可读可调,BindingFlags 过滤可见性(示例只用 DeclaredOnly 公共实例成员,避开 get_Xxx 编译器生成方法)。

Go:reflect 包(示例)能读结构体字段与方法,但有边界——非导出字段不可见、方法集区分值/指针接收者(示例用 reflect.TypeOf(&Point{}) 让 Move 可见)、性能开销大;Go 的惯用法是少用反射、多用接口断言。

Java:Class 对象(示例)+ getDeclaredMethods/getDeclaredFields,配合 setAccessible 可越过 private——动态代理、依赖注入、JUnit 全靠它。

JavaScript:没有正式「反射 API」这一说(示例用对象/原型自省近似);Object.keys 只列自有可枚举属性,方法藏在原型上要 getOwnPropertyNames(Point.prototype) 才能拿到。

Python:inspect 模块(示例)+ __dict__/__annotations__;动态属性意味着自省永远「近似」——运行时新增的实例属性不会出现在类注解里,这正是动态与静态元数据的分野。

Rust:彻底无运行时反射(示例如实展示):类型在编译后不保留名字/成员清单,std::any::type_name 只是编译期字符串、std::any::Any 只能向下转型;serde/derive 宏的「反射」全是编译期代码生成——这就是编译型语言与动态语言的能力分野。

TypeScript:类型信息只存在于编译期(示例与 JS 同),interface/type 编译后消失——想要运行时元数据得靠装饰器(实验性)或手写映射表。