Go学习笔记-Reflection

反射是Go语言的高级特性,允许程序在运行时检查类型和值的信息。虽然反射功能强大,但应该谨慎使用,因为它会影响性能并降低代码的类型安全性。

反射基础

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package main

import (
    "fmt"
    "reflect"
    "time"
)

// 1. 基本反射操作
func basicReflection() {
    fmt.Println("=== 基本反射操作 ===")
    
    var x float64 = 3.14
    var s string = "hello"
    var b bool = true
    
    // 获取类型信息
    fmt.Printf("x的类型: %v\n", reflect.TypeOf(x))
    fmt.Printf("s的类型: %v\n", reflect.TypeOf(s))
    fmt.Printf("b的类型: %v\n", reflect.TypeOf(b))
    
    // 获取值信息
    fmt.Printf("x的值: %v\n", reflect.ValueOf(x))
    fmt.Printf("s的值: %v\n", reflect.ValueOf(s))
    fmt.Printf("b的值: %v\n", reflect.ValueOf(b))
    
    // 获取类型的种类
    fmt.Printf("x的种类: %v\n", reflect.TypeOf(x).Kind())
    fmt.Printf("s的种类: %v\n", reflect.TypeOf(s).Kind())
    fmt.Printf("b的种类: %v\n", reflect.TypeOf(b).Kind())
    
    // 从反射值获取接口值
    v := reflect.ValueOf(x)
    fmt.Printf("从反射值获取: %v (类型: %T)\n", v.Interface(), v.Interface())
}

// 2. 反射修改值
func reflectionModification() {
    fmt.Println("\n=== 反射修改值 ===")
    
    var x float64 = 3.14
    fmt.Printf("修改前: %v\n", x)
    
    // 获取指针的反射值
    v := reflect.ValueOf(&x)
    fmt.Printf("指针类型: %v\n", v.Type())
    fmt.Printf("指针种类: %v\n", v.Kind())
    
    // 获取指针指向的元素
    elem := v.Elem()
    fmt.Printf("元素类型: %v\n", elem.Type())
    fmt.Printf("元素种类: %v\n", elem.Kind())
    fmt.Printf("是否可设置: %v\n", elem.CanSet())
    
    // 修改值
    if elem.CanSet() {
        elem.SetFloat(2.71)
        fmt.Printf("修改后: %v\n", x)
    }
    
    // 字符串修改示例
    var str string = "hello"
    strPtr := reflect.ValueOf(&str)
    strElem := strPtr.Elem()
    
    if strElem.CanSet() {
        strElem.SetString("world")
        fmt.Printf("字符串修改后: %v\n", str)
    }
}

// 3. 切片和数组反射
func sliceArrayReflection() {
    fmt.Println("\n=== 切片和数组反射 ===")
    
    // 切片反射
    slice := []int{1, 2, 3, 4, 5}
    sliceValue := reflect.ValueOf(slice)
    
    fmt.Printf("切片类型: %v\n", sliceValue.Type())
    fmt.Printf("切片长度: %d\n", sliceValue.Len())
    fmt.Printf("切片容量: %d\n", sliceValue.Cap())
    
    // 遍历切片元素
    fmt.Print("切片元素: ")
    for i := 0; i < sliceValue.Len(); i++ {
        elem := sliceValue.Index(i)
        fmt.Printf("%v ", elem.Interface())
    }
    fmt.Println()
    
    // 修改切片元素
    slicePtr := reflect.ValueOf(&slice)
    sliceElem := slicePtr.Elem()
    
    if sliceElem.Index(0).CanSet() {
        sliceElem.Index(0).SetInt(100)
        fmt.Printf("修改后的切片: %v\n", slice)
    }
    
    // 数组反射
    array := [3]string{"a", "b", "c"}
    arrayValue := reflect.ValueOf(array)
    
    fmt.Printf("数组类型: %v\n", arrayValue.Type())
    fmt.Printf("数组长度: %d\n", arrayValue.Len())
    
    fmt.Print("数组元素: ")
    for i := 0; i < arrayValue.Len(); i++ {
        elem := arrayValue.Index(i)
        fmt.Printf("%v ", elem.Interface())
    }
    fmt.Println()
}

// 4. 映射反射
func mapReflection() {
    fmt.Println("\n=== 映射反射 ===")
    
    m := map[string]int{
        "apple":  5,
        "banana": 3,
        "cherry": 8,
    }
    
    mapValue := reflect.ValueOf(m)
    fmt.Printf("映射类型: %v\n", mapValue.Type())
    fmt.Printf("映射长度: %d\n", mapValue.Len())
    
    // 获取所有键
    keys := mapValue.MapKeys()
    fmt.Print("映射键: ")
    for _, key := range keys {
        fmt.Printf("%v ", key.Interface())
    }
    fmt.Println()
    
    // 遍历映射
    fmt.Println("映射内容:")
    for _, key := range keys {
        value := mapValue.MapIndex(key)
        fmt.Printf("  %v: %v\n", key.Interface(), value.Interface())
    }
    
    // 设置映射值
    mapPtr := reflect.ValueOf(&m)
    mapElem := mapPtr.Elem()
    
    newKey := reflect.ValueOf("date")
    newValue := reflect.ValueOf(12)
    mapElem.SetMapIndex(newKey, newValue)
    
    fmt.Printf("添加新元素后: %v\n", m)
    
    // 删除映射元素
    deleteKey := reflect.ValueOf("banana")
    mapElem.SetMapIndex(deleteKey, reflect.Value{})
    
    fmt.Printf("删除元素后: %v\n", m)
}

func main() {
    basicReflection()
    reflectionModification()
    sliceArrayReflection()
    mapReflection()
}

结构体反射

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package main

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

// 1. 示例结构体
type Person struct {
    Name    string `json:"name" validate:"required"`
    Age     int    `json:"age" validate:"min=0,max=150"`
    Email   string `json:"email" validate:"email"`
    Address Address `json:"address"`
    private string  // 私有字段
}

type Address struct {
    Street  string `json:"street"`
    City    string `json:"city"`
    Country string `json:"country"`
}

// 2. 结构体字段反射
func structFieldReflection() {
    fmt.Println("=== 结构体字段反射 ===")
    
    person := Person{
        Name:  "张三",
        Age:   30,
        Email: "zhangsan@example.com",
        Address: Address{
            Street:  "中关村大街1号",
            City:    "北京",
            Country: "中国",
        },
        private: "私有数据",
    }
    
    personType := reflect.TypeOf(person)
    personValue := reflect.ValueOf(person)
    
    fmt.Printf("结构体类型: %v\n", personType)
    fmt.Printf("字段数量: %d\n", personType.NumField())
    
    // 遍历所有字段
    for i := 0; i < personType.NumField(); i++ {
        field := personType.Field(i)
        value := personValue.Field(i)
        
        fmt.Printf("字段 %d:\n", i)
        fmt.Printf("  名称: %s\n", field.Name)
        fmt.Printf("  类型: %v\n", field.Type)
        fmt.Printf("  标签: %s\n", field.Tag)
        
        // 检查字段是否可导出
        if value.CanInterface() {
            fmt.Printf("  值: %v\n", value.Interface())
        } else {
            fmt.Printf("  值: <不可访问>\n")
        }
        
        // 获取特定标签
        if jsonTag := field.Tag.Get("json"); jsonTag != "" {
            fmt.Printf("  JSON标签: %s\n", jsonTag)
        }
        
        if validateTag := field.Tag.Get("validate"); validateTag != "" {
            fmt.Printf("  验证标签: %s\n", validateTag)
        }
        
        fmt.Println()
    }
}

// 3. 按名称访问字段
func fieldByName() {
    fmt.Println("=== 按名称访问字段 ===")
    
    person := Person{
        Name: "李四",
        Age:  25,
        Email: "lisi@example.com",
    }
    
    personValue := reflect.ValueOf(person)
    personType := reflect.TypeOf(person)
    
    // 按名称获取字段
    fieldNames := []string{"Name", "Age", "Email", "Address"}
    
    for _, fieldName := range fieldNames {
        if field, found := personType.FieldByName(fieldName); found {
            value := personValue.FieldByName(fieldName)
            
            fmt.Printf("字段 %s:\n", fieldName)
            fmt.Printf("  类型: %v\n", field.Type)
            
            if value.CanInterface() {
                fmt.Printf("  值: %v\n", value.Interface())
            }
        } else {
            fmt.Printf("字段 %s 不存在\n", fieldName)
        }
    }
}

// 4. 修改结构体字段
func modifyStructFields() {
    fmt.Println("\n=== 修改结构体字段 ===")
    
    person := Person{
        Name: "王五",
        Age:  28,
        Email: "wangwu@example.com",
    }
    
    fmt.Printf("修改前: %+v\n", person)
    
    // 获取指针的反射值
    personPtr := reflect.ValueOf(&person)
    personElem := personPtr.Elem()
    
    // 修改Name字段
    nameField := personElem.FieldByName("Name")
    if nameField.IsValid() && nameField.CanSet() {
        nameField.SetString("王五(已修改)")
    }
    
    // 修改Age字段
    ageField := personElem.FieldByName("Age")
    if ageField.IsValid() && ageField.CanSet() {
        ageField.SetInt(30)
    }
    
    // 修改嵌套结构体
    addressField := personElem.FieldByName("Address")
    if addressField.IsValid() && addressField.CanSet() {
        newAddress := Address{
            Street:  "朝阳路100号",
            City:    "北京",
            Country: "中国",
        }
        addressField.Set(reflect.ValueOf(newAddress))
    }
    
    fmt.Printf("修改后: %+v\n", person)
}

// 5. 结构体标签处理
func structTagProcessing() {
    fmt.Println("\n=== 结构体标签处理 ===")
    
    personType := reflect.TypeOf(Person{})
    
    for i := 0; i < personType.NumField(); i++ {
        field := personType.Field(i)
        
        fmt.Printf("字段: %s\n", field.Name)
        
        // 解析JSON标签
        if jsonTag := field.Tag.Get("json"); jsonTag != "" {
            parts := strings.Split(jsonTag, ",")
            jsonName := parts[0]
            fmt.Printf("  JSON名称: %s\n", jsonName)
            
            if len(parts) > 1 {
                fmt.Printf("  JSON选项: %v\n", parts[1:])
            }
        }
        
        // 解析验证标签
        if validateTag := field.Tag.Get("validate"); validateTag != "" {
            rules := strings.Split(validateTag, ",")
            fmt.Printf("  验证规则:\n")
            
            for _, rule := range rules {
                if strings.Contains(rule, "=") {
                    parts := strings.Split(rule, "=")
                    fmt.Printf("    %s: %s\n", parts[0], parts[1])
                } else {
                    fmt.Printf("    %s\n", rule)
                }
            }
        }
        
        fmt.Println()
    }
}

// 6. 动态创建结构体实例
func dynamicStructCreation() {
    fmt.Println("=== 动态创建结构体实例 ===")
    
    // 获取Person类型
    personType := reflect.TypeOf(Person{})
    
    // 创建新实例
    personValue := reflect.New(personType).Elem()
    
    // 设置字段值
    personValue.FieldByName("Name").SetString("动态创建")
    personValue.FieldByName("Age").SetInt(35)
    personValue.FieldByName("Email").SetString("dynamic@example.com")
    
    // 创建嵌套结构体
    addressType := reflect.TypeOf(Address{})
    addressValue := reflect.New(addressType).Elem()
    addressValue.FieldByName("Street").SetString("动态街道")
    addressValue.FieldByName("City").SetString("动态城市")
    addressValue.FieldByName("Country").SetString("动态国家")
    
    personValue.FieldByName("Address").Set(addressValue)
    
    // 获取创建的实例
    person := personValue.Interface().(Person)
    fmt.Printf("动态创建的实例: %+v\n", person)
}

// 7. 结构体比较
func structComparison() {
    fmt.Println("\n=== 结构体比较 ===")
    
    person1 := Person{Name: "张三", Age: 30}
    person2 := Person{Name: "张三", Age: 30}
    person3 := Person{Name: "李四", Age: 25}
    
    // 使用反射比较结构体
    compareStructs := func(a, b interface{}) bool {
        va := reflect.ValueOf(a)
        vb := reflect.ValueOf(b)
        
        if va.Type() != vb.Type() {
            return false
        }
        
        return reflect.DeepEqual(a, b)
    }
    
    fmt.Printf("person1 == person2: %t\n", compareStructs(person1, person2))
    fmt.Printf("person1 == person3: %t\n", compareStructs(person1, person3))
    
    // 字段级比较
    compareFields := func(a, b interface{}, fieldName string) bool {
        va := reflect.ValueOf(a)
        vb := reflect.ValueOf(b)
        
        fieldA := va.FieldByName(fieldName)
        fieldB := vb.FieldByName(fieldName)
        
        if !fieldA.IsValid() || !fieldB.IsValid() {
            return false
        }
        
        return reflect.DeepEqual(fieldA.Interface(), fieldB.Interface())
    }
    
    fmt.Printf("person1.Name == person2.Name: %t\n", 
        compareFields(person1, person2, "Name"))
    fmt.Printf("person1.Age == person3.Age: %t\n", 
        compareFields(person1, person3, "Age"))
}

func main() {
    structFieldReflection()
    fieldByName()
    modifyStructFields()
    structTagProcessing()
    dynamicStructCreation()
    structComparison()
}

方法反射和高级用法

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package main

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

// 1. 示例类型和方法
type Calculator struct {
    result float64
}

func (c *Calculator) Add(a, b float64) float64 {
    c.result = a + b
    return c.result
}

func (c *Calculator) Multiply(a, b float64) float64 {
    c.result = a * b
    return c.result
}

func (c Calculator) GetResult() float64 {
    return c.result
}

func (c *Calculator) Reset() {
    c.result = 0
}

func (c Calculator) String() string {
    return fmt.Sprintf("Calculator{result: %.2f}", c.result)
}

// 2. 方法反射
func methodReflection() {
    fmt.Println("=== 方法反射 ===")
    
    calc := &Calculator{}
    calcType := reflect.TypeOf(calc)
    calcValue := reflect.ValueOf(calc)
    
    fmt.Printf("类型: %v\n", calcType)
    fmt.Printf("方法数量: %d\n", calcType.NumMethod())
    
    // 遍历所有方法
    for i := 0; i < calcType.NumMethod(); i++ {
        method := calcType.Method(i)
        fmt.Printf("方法 %d: %s\n", i, method.Name)
        fmt.Printf("  类型: %v\n", method.Type)
        fmt.Printf("  输入参数数量: %d\n", method.Type.NumIn())
        fmt.Printf("  输出参数数量: %d\n", method.Type.NumOut())
        
        // 打印参数类型
        for j := 0; j < method.Type.NumIn(); j++ {
            fmt.Printf("    输入参数 %d: %v\n", j, method.Type.In(j))
        }
        
        for j := 0; j < method.Type.NumOut(); j++ {
            fmt.Printf("    输出参数 %d: %v\n", j, method.Type.Out(j))
        }
        
        fmt.Println()
    }
    
    // 按名称获取方法
    if method := calcValue.MethodByName("Add"); method.IsValid() {
        fmt.Println("找到Add方法")
        
        // 调用方法
        args := []reflect.Value{
            reflect.ValueOf(10.0),
            reflect.ValueOf(20.0),
        }
        
        results := method.Call(args)
        if len(results) > 0 {
            fmt.Printf("Add(10, 20) = %v\n", results[0].Interface())
        }
    }
}

// 3. 动态方法调用
func dynamicMethodCall() {
    fmt.Println("\n=== 动态方法调用 ===")
    
    calc := &Calculator{}
    calcValue := reflect.ValueOf(calc)
    
    // 定义要调用的方法和参数
    methodCalls := []struct {
        methodName string
        args       []interface{}
    }{
        {"Add", []interface{}{5.0, 3.0}},
        {"Multiply", []interface{}{4.0, 6.0}},
        {"Reset", []interface{}{}},
        {"Add", []interface{}{1.0, 2.0}},
    }
    
    for _, call := range methodCalls {
        method := calcValue.MethodByName(call.methodName)
        if !method.IsValid() {
            fmt.Printf("方法 %s 不存在\n", call.methodName)
            continue
        }
        
        // 准备参数
        args := make([]reflect.Value, len(call.args))
        for i, arg := range call.args {
            args[i] = reflect.ValueOf(arg)
        }
        
        // 调用方法
        fmt.Printf("调用 %s(%v)\n", call.methodName, call.args)
        results := method.Call(args)
        
        // 处理返回值
        if len(results) > 0 {
            fmt.Printf("  返回值: %v\n", results[0].Interface())
        }
        
        // 显示当前状态
        if getResult := calcValue.MethodByName("GetResult"); getResult.IsValid() {
            currentResult := getResult.Call(nil)
            fmt.Printf("  当前结果: %v\n", currentResult[0].Interface())
        }
        
        fmt.Println()
    }
}

// 4. 接口反射
func interfaceReflection() {
    fmt.Println("=== 接口反射 ===")
    
    var stringer fmt.Stringer = &Calculator{result: 42.0}
    
    stringerValue := reflect.ValueOf(stringer)
    stringerType := reflect.TypeOf(stringer)
    
    fmt.Printf("接口类型: %v\n", stringerType)
    fmt.Printf("接口种类: %v\n", stringerType.Kind())
    
    // 获取接口的具体类型
    concreteType := stringerValue.Elem().Type()
    fmt.Printf("具体类型: %v\n", concreteType)
    
    // 调用接口方法
    if method := stringerValue.MethodByName("String"); method.IsValid() {
        result := method.Call(nil)
        fmt.Printf("String() = %v\n", result[0].Interface())
    }
    
    // 类型断言
    if stringerValue.Type().Implements(reflect.TypeOf((*fmt.Stringer)(nil)).Elem()) {
        fmt.Println("实现了fmt.Stringer接口")
    }
}

// 5. 函数反射
func functionReflection() {
    fmt.Println("\n=== 函数反射 ===")
    
    // 定义一些函数
    add := func(a, b int) int { return a + b }
    multiply := func(a, b float64) float64 { return a * b }
    greet := func(name string) string { return "Hello, " + name }
    
    functions := map[string]interface{}{
        "add":      add,
        "multiply": multiply,
        "greet":    greet,
    }
    
    for name, fn := range functions {
        fnValue := reflect.ValueOf(fn)
        fnType := reflect.TypeOf(fn)
        
        fmt.Printf("函数 %s:\n", name)
        fmt.Printf("  类型: %v\n", fnType)
        fmt.Printf("  种类: %v\n", fnType.Kind())
        fmt.Printf("  输入参数数量: %d\n", fnType.NumIn())
        fmt.Printf("  输出参数数量: %d\n", fnType.NumOut())
        
        // 根据函数类型调用
        switch name {
        case "add":
            args := []reflect.Value{
                reflect.ValueOf(10),
                reflect.ValueOf(20),
            }
            results := fnValue.Call(args)
            fmt.Printf("  add(10, 20) = %v\n", results[0].Interface())
            
        case "multiply":
            args := []reflect.Value{
                reflect.ValueOf(3.14),
                reflect.ValueOf(2.0),
            }
            results := fnValue.Call(args)
            fmt.Printf("  multiply(3.14, 2.0) = %v\n", results[0].Interface())
            
        case "greet":
            args := []reflect.Value{
                reflect.ValueOf("World"),
            }
            results := fnValue.Call(args)
            fmt.Printf("  greet(\"World\") = %v\n", results[0].Interface())
        }
        
        fmt.Println()
    }
}

// 6. 反射性能考虑
func reflectionPerformance() {
    fmt.Println("=== 反射性能考虑 ===")
    
    calc := &Calculator{}
    
    // 直接调用
    start := time.Now()
    for i := 0; i < 1000000; i++ {
        calc.Add(1.0, 2.0)
    }
    directTime := time.Since(start)
    
    // 反射调用
    calcValue := reflect.ValueOf(calc)
    addMethod := calcValue.MethodByName("Add")
    args := []reflect.Value{
        reflect.ValueOf(1.0),
        reflect.ValueOf(2.0),
    }
    
    start = time.Now()
    for i := 0; i < 1000000; i++ {
        addMethod.Call(args)
    }
    reflectTime := time.Since(start)
    
    fmt.Printf("直接调用耗时: %v\n", directTime)
    fmt.Printf("反射调用耗时: %v\n", reflectTime)
    fmt.Printf("反射开销: %.2fx\n", float64(reflectTime)/float64(directTime))
}

// 7. 实用反射工具函数
func utilityFunctions() {
    fmt.Println("\n=== 实用反射工具函数 ===")
    
    // 检查是否为零值
    isZeroValue := func(v interface{}) bool {
        value := reflect.ValueOf(v)
        zero := reflect.Zero(value.Type())
        return reflect.DeepEqual(value.Interface(), zero.Interface())
    }
    
    fmt.Printf("isZeroValue(0): %t\n", isZeroValue(0))
    fmt.Printf("isZeroValue(42): %t\n", isZeroValue(42))
    fmt.Printf("isZeroValue(\"\"): %t\n", isZeroValue(""))
    fmt.Printf("isZeroValue(\"hello\"): %t\n", isZeroValue("hello"))
    
    // 获取类型名称
    getTypeName := func(v interface{}) string {
        t := reflect.TypeOf(v)
        if t.Kind() == reflect.Ptr {
            return "*" + t.Elem().Name()
        }
        return t.Name()
    }
    
    calc := &Calculator{}
    fmt.Printf("getTypeName(calc): %s\n", getTypeName(calc))
    fmt.Printf("getTypeName(42): %s\n", getTypeName(42))
    fmt.Printf("getTypeName(\"hello\"): %s\n", getTypeName("hello"))
    
    // 深度拷贝
    deepCopy := func(src interface{}) interface{} {
        srcValue := reflect.ValueOf(src)
        if srcValue.Kind() == reflect.Ptr {
            srcValue = srcValue.Elem()
        }
        
        dstValue := reflect.New(srcValue.Type()).Elem()
        dstValue.Set(srcValue)
        
        return dstValue.Interface()
    }
    
    original := Calculator{result: 42.0}
    copied := deepCopy(original).(Calculator)
    
    fmt.Printf("原始: %+v\n", original)
    fmt.Printf("拷贝: %+v\n", copied)
    
    // 修改拷贝不影响原始
    copied.result = 100.0
    fmt.Printf("修改后原始: %+v\n", original)
    fmt.Printf("修改后拷贝: %+v\n", copied)
}

func main() {
    methodReflection()
    dynamicMethodCall()
    interfaceReflection()
    functionReflection()
    reflectionPerformance()
    utilityFunctions()
}

总结

  1. 反射基础

    • reflect.TypeOf() - 获取类型信息
    • reflect.ValueOf() - 获取值信息
    • reflect.Kind() - 获取基础类型种类
    • Interface() - 从反射值获取原始值
  2. 值修改

    • 使用指针获取可修改的反射值
    • CanSet() - 检查是否可设置
    • SetXxx() - 设置不同类型的值
    • Elem() - 获取指针指向的元素
  3. 结构体反射

    • NumField() - 获取字段数量
    • Field() / FieldByName() - 访问字段
    • 结构体标签处理
    • 动态创建和修改结构体
  4. 方法反射

    • NumMethod() - 获取方法数量
    • Method() / MethodByName() - 访问方法
    • Call() - 动态调用方法
    • 接口和函数反射
  5. 最佳实践

    • 谨慎使用反射,优先考虑类型安全的方案
    • 注意反射的性能开销
    • 使用反射进行框架和库开发
    • 合理处理反射中的错误情况
    • 缓存反射信息以提高性能
updatedupdated2025-09-202025-09-20