反射
package main
import (
"fmt"
"reflect"
)
type User struct {
Id int
Name string
Age int
}
func (u User) Hello() {
fmt.Println("Hello World")
}
func main() {
u := User{1, "ok", 12}
Info(u)
}
func Info(o interface{}) {
t := reflect.TypeOf(o)
fmt.Println("Type:", t.Name())
if k := t.Kind(); k != reflect.Struct {
fmt.Println("xxxx")
return
}
v := reflect.ValueOf(o)
fmt.Println("Fields:")
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
val := v.Field(i).Interface()
fmt.Printf("%6s: %v = %v\n", f.Name, f.Type, val)
}
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
fmt.Printf("%6s: %v\n", m.Name, m.Type)
}
}
获取字段内容
package main
import (
"fmt"
"reflect"
)
type User struct {
Id int
Name string
Age int
}
type Manager struct {
User
title string
}
func main() {
m := Manager{User: User{1, "ok", 12}, title: "123"}
t := reflect.TypeOf(m)
fmt.Printf("%#v\n", t.FieldByIndex([]int{0, 0}))
}
通过反射修改基本类型
package main
import (
"fmt"
"reflect"
)
func main() {
x := 123
v := reflect.ValueOf(&x)
v.Elem().SetInt(999)
fmt.Println(x)
}
通过反射对接口中的对象的值进行修改
package main
import (
"fmt"
"reflect"
)
type User struct {
Id int
Name string
Age int
}
func main() {
u := User{1, "ok", 12}
Set(&u)
fmt.Println(u)
}
func Set(o interface{}) {
v := reflect.ValueOf(o)
if v.Kind() == reflect.Ptr && !v.Elem().CanSet() {
fmt.Println("xx")
return
}
v = v.Elem()
f := v.FieldByName("Name")
if !f.IsValid() {
fmt.Println("BAD")
return
}
if f.Kind() == reflect.String {
f.SetString("BYEBYE")
}
}
通过反射进行方法调用
package main
import (
"fmt"
"reflect"
)
type User struct {
Id int
Name string
Age int
}
func (u User) Hello(name string) {
fmt.Println("Hello", name, ", my name is", u.Name)
}
func main() {
u := User{1, "ok", 12}
u.Hello("wang")
v := reflect.ValueOf(u)
mv := v.MethodByName("Hello")
args := []reflect.Value{reflect.ValueOf("wang")}
mv.Call(args)
}