加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

013.反射reflection

发布时间:2020-12-16 19:18:17 所属栏目:大数据 来源:网络整理
导读:反射reflection 反射可大大提高程序的灵活性,使得 interface{} 有更大的发挥余地 反射使用 TypeOf 和 ValueOf 函数从接口中获取目标对象信息 反射会将匿名字段作为独立字段(匿名字段本质) 想要利用反射修改对象状态,前提是 interface.data 是 settable,

反射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 World.")
}

//私有方法
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())

    v := reflect.ValueOf(o)
    fmt.Println("Fields:")

    fmt.Println(t.Kind(),reflect.Struct)

    //如果类型不等于struct,打印
    if k := t.Kind(); k != reflect.Struct {
        fmt.Println("Error...")
        return
    }

    //遍历所有的字段
    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 : %vn",m.Name,m.Type)
    }
}

package main

import (
    "fmt"
    "reflect"
)

type User struct {
    Id   int
    Name string
    Age  int
}

type Manager struct {
    User  User
    title string
}

func main() {
    m := Manager{User: User{1, 12},title: "123"}
    t := reflect.TypeOf(m)

    //取title
    fmt.Printf("%#vn",t.Field(1))
    fmt.Println()
    //取User中的Name
    fmt.Printf("%#vn",t.FieldByIndex([]int{0, 1}))
}

package main

import (
    "fmt"
    "reflect"
)

func main() {
    x := 123
    //要取x的地址
    v := reflect.ValueOf(&x)
    //通过指针获取到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", 10}
    Set(&u)
    fmt.Println(u)
}

func Set(o interface{}) {
    v := reflect.ValueOf(o)

    if v.Kind() == reflect.Ptr && !v.Elem().CanSet() {
        fmt.Println("Error...")
        return
    } else {
        v = v.Elem()
    }

    f := v.FieldByName("Name")
    if !f.IsValid() {
        fmt.Println("BAD...")
        return
    }

    if f.Kind() == reflect.String {
        f.SetString("Hello")
    }
}

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, 10}
    v := reflect.ValueOf(u)
    mv := v.MethodByName("Hello")

    args := []reflect.Value{reflect.ValueOf("XiaoMing")}
    mv.Call(args)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读