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()
}
|