Golang 反射
反射是
示例
运行时获取、修改对象内部结构的能力
函数reflect.TypeOf()
reflect.ValueOf()
示例
package basicTest
import (
"fmt"
"reflect"
)
func (u User) GetName() string {
return u.Name
}
func (u User) GetAge() int {
return u.Age
}
type User struct {
Name string
Age int
}
func ReflectLearn() {
user := User{"jihite", 25}
// TypeOf
t := reflect.TypeOf(user)
fmt.Println(t)
// ValueOf
v := reflect.ValueOf(user)
fmt.Println(v)
// Interface
u1 := v.Interface().(User)
fmt.Println(u1)
// type 底层类型
fmt.Println(t.Kind())
fmt.Println(v.Kind())
// 遍历字段
for i := 0; i < t.NumField(); i = i + 1 {
key := t.Field(i)
value := v.Field(i).Interface()
fmt.Printf("第%d个字段是:%s, 类型:%s, 值:%s\n", i, key.Name, key.Type, value)
}
// 遍历函数
for i := 0; i < t.NumMethod(); i = i + 1 {
m := t.Method(i)
fmt.Printf("第%d个函数:%s, 类型:%s\n", i, m.Name, m.Type)
}
}
版权声明
本文仅代表作者观点,不代表博信信息网立场。