前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >013.反射reflection

013.反射reflection

作者头像
qubianzhong
发布2018-08-15 17:05:49
2080
发布2018-08-15 17:05:49
举报
文章被收录于专栏:行者常至行者常至行者常至

反射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 : %v\n", 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, "OK", 12}, title: "123"}
    t := reflect.TypeOf(m)

    //取title
    fmt.Printf("%#v\n", t.Field(1))
    fmt.Println()
    //取User中的Name
    fmt.Printf("%#v\n", 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, "ok", 10}
    v := reflect.ValueOf(u)
    mv := v.MethodByName("Hello")

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年06月06日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 反射reflection
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档