十三.Go反射reflection

96
kaxi4it
0.1 2017.06.24 23:42* 字数 106

反射reflection

  • 反射可大大提高程序的灵猴性,使得interface{}有更大的发挥余地
  • 反射使用TypeOf和ValueOf函数从接口中获取目标对象信息
  • 反射会将匿名字段作为独立字段(匿名字段本质)
  • 想要利用反射修改对象状态,前提是interface.data是settable,即pointer-interface
  • 通过反射可以“动态”调用方法
package main
import (
    "fmt"
    "reflect"
)
type User struct {
    Id   int
    Name string
    Age  int
}
func (u User) Hello() {
    fmt.Println("hello")
}
func main() {
    u := User{1, "ok", 12}
    Info(u)
}
func Info(o interface{}) {
    t := reflect.TypeOf(o)
    fmt.Println("type", t.Name())
    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", 11}, title: "123"}
    t := reflect.TypeOf(m)
    fmt.Printf("%#v\n", t.Field(0))
    fmt.Printf("%#v\n", t.FieldByIndex([]int{0, 1}))
}
package main
import (
    "fmt"
    "reflect"
)
type User struct {
    Id   int
    Name string
    Age  int
}
func main() {
    x := 123
    v := reflect.ValueOf(&x)
    v.Elem().SetInt(999)
    fmt.Println(x)
    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("no")
        return
    } else {
        v = v.Elem()
    }
    f := v.FieldByName("Name")
    if !f.IsValid() {
        fmt.Println("no")
        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}
    v := reflect.ValueOf(u)
    mv := v.MethodByName("Hello")
    args := []reflect.Value{reflect.ValueOf("joe")}
    mv.Call(args)
}
Golang编程基础
Web note ad 1