《Go学习笔记 . 雨痕》反射

一、类型(Type)

反射(reflect)让我们能在运行期探知对象的类型信息和内存结构,这从一定程度上弥(mi)补了静态语言在动态行为上的不足。同时,反射还是实现元编程的重要手段。

和 C 数据结构一样,Go 对象头部并没有类型指针,通过其自身是无法在运行期获知任何类型相关信息的。反射操作所需要的全部信息都源自接口变量。接口变量除存储自身类型外,还会保存实际对象的类型数据。

func TypeOf(i interface{}) Type
func ValueOf(i interface{}) Value

这 两个 反射入口函数,会将任何传入的对象转换为接口类型。

在面对类型时,需要区分 Type 和 Kind。前者表示真实类型(静态类型),后者表示其基础结构(底层类型)类别 -- 基类型。

type X int

func main() {
        var a X = 100
        t := reflect.TypeOf(a)

        fmt.Println(t)
        fmt.Println(t.Name(), t.Kind())
}

输出:

X  int

所以在类型判断上,须选择正确的方式

type X int
type Y int

func main() {
        var a, b X = 100, 200
        var c Y = 300

        ta, tb, tc := reflect.TypeOf(a), reflect.TypeOf(b), reflect.TypeOf(c)

        fmt.Println(ta == tb, ta == tc)
        fmt.Println(ta.Kind() == tc.Kind())
}

除通过实际对象获取类型外,也可直接构造一些基础复合类型。

func main() {
        a := reflect.ArrayOf(10, reflect.TypeOf(byte(0)))
        m := reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf(0))

        fmt.Println(a, m)
}

输出:

[10]uint8     map[string]int

传入对象 应区分 基类型 和 指针类型,因为它们并不属于同一类型。

func main() {
        x := 100

        tx, tp := reflect.TypeOf(x), reflect.TypeOf(&x)
        fmt.Println(tx, tp, tx == tp)

        fmt.Println(tx.Kind(), tp.Kind())
        fmt.Println(tx == tp.Elem())
}

输出:

int *int false
int ptr
true

方法 Elem() 返回 指针、数组、切片、字典(值)或 通道的 基类型。

func main() {
        fmt.Println(reflect.TypeOf(map[string]int{}).Elem())
        fmt.Println(reflect.TypeOf([]int32{}).Elem())
}

输出:

int
int32

只有在获取 结构体指针 的 基类型 后,才能遍历它的字段。

type user struct {
        name string
        age int
}

type manager struct {
        user
        title string
}

func main() {
        var m manager
        t := reflect.TypeOf(&m)

        if t.Kind() == reflect.Ptr {
                t = t.Elem()
        }

        for i := 0; i < t.NumField(); i++ {
                f := t.Field(i)
                fmt.Println(f.Name, f.Type, f.Offset)
                if f.Anonymous { // 输出匿名字段结构
                        for x := 0; x < f.Type.NumField(); x++ {
                                af := f.Type.Field(x)
                                fmt.Println(" ", af.Name, af.Type)
                        }
                }
        }
}

输出:

user main.user 0
  name string
  age int
title string 24

对于匿名字段,可用多级索引(按照定义顺序)直接访问。

type user struct {
        name string
        age  int
}

type manager struct {
        user
        title string
}

func main() {
        var m manager

        t := reflect.TypeOf(m)

        name, _ := t.FieldByName("name") // 按名称查找
        fmt.Println(name.Name, name.Type)

        age := t.FieldByIndex([]int{0, 1}) // 按多级索引查找
        fmt.Println(age.Name, age.Type)
}

输出:

name string
age int

FieldByName() 不支持多级名称,如有同名遮蔽,须通过匿名字段二次获取。

同样地,输出方法集时,一样区分 基类型 和 指针类型。

type A int

type B struct {
        A
}

func (A) av() {}
func (*A) ap() {}

func (B) bv() {}
func (*B) bp() {}

func main() {
        var b B

        t := reflect.TypeOf(&b)
        s := []reflect.Type{t, t.Elem()}

        for _, t2 := range s {
                fmt.Println(t2, ":")

                for i := 0; i < t2.NumMethod(); i++ {
                        fmt.Println(" ", t2.Method(i))
                }
        }
}

输出:

*main.B :
    {ap main func(*main.B) <func(*main.B) Value> 0}
    {av main func(*main.B) <func(*main.B) Value> 1}
    {bp main func(*main.B) <func(*main.B) Value> 2}
    {bv main func(*main.B) <func(*main.B) Value> 3}      

main.B :
    {av main func(*main.B) <func(*main.B) Value> 0}  
    {bv main func(*main.B) <func(*main.B) Value> 1}   

有一点和想象的不同,反射能探知当前包或外包的非导出结构成员。

import (
        "net/http"
        "reflect"
        "fmt"
)

func main()  {
        var s http.Server
        t := reflect.TypeOf(s)

        for i := 0; i < t.NumField(); i++ {
                fmt.Println(t.Field(i).Name)
        }
}

输出:

Addr
Handler
ReadTimeout
WriteTimeout
TLSConfig
MaxHeaderBytes
TLSNextProto
ConnState
ErrorLog
disableKeepAlives
nextProtoOnce
nextProtoErr

相对 reflect 而言,当前包 和 外包 都是“外包”。

可用反射提取 struct tag,还能自动分解。其常用于 ORM 映射,或数据格式验证。

type user struct {
        name string `field:"name" type:"varchar(50)"`
        age  int `field:"age" type:"int"`
}

func main() {
        var u user
        t := reflect.TypeOf(u)

        for i := 0; i < t.NumField(); i++ {
                f := t.Field(i)
                fmt.Printf("%s: %s %s\n", f.Name, f.Tag.Get("field"), f.Tag.Get("type"))
        }
}

输出:

name: name varchar(50)
age: age int

辅助判断方法 Implements()、ConvertibleTo、AssignableTo() 都是运行期进行 动态调用赋值 所必需的。

type X int

func (X) String() string {
        return ""
}

func main()  {
        var a X
        t := reflect.TypeOf(a)

        // Implements 不能直接使用类型作为参数,导致这种用法非常别扭
        st := reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
        fmt.Println(t.Implements(st))

        it := reflect.TypeOf(0)
        fmt.Println(t.ConvertibleTo(it))

        fmt.Println(t.AssignableTo(st), t.AssignableTo(it))
}

输出:

true
true
true false

二、值(Value)

和 Type 获取类型信息不同,Value 专注于对象实例数据读写。

在前面章节曾提到过,接口变量会复制对象,且是 unaddressable 的,所以要想修改目标对象,就必须使用指针。

func main()  {
        a := 100
        va, vp := reflect.ValueOf(a), reflect.ValueOf(&a).Elem()

        fmt.Println(va.CanAddr(), va.CanSet())
        fmt.Println(vp.CanAddr(), vp.CanSet())
}

输出:

false false
true true

就算传入指针,一样需要通过 Elem() 获取目标对象。因为被接口存储的指针本身是不能寻址和进行设置操作的。

注意,不能对非导出字段直接进行设置操作,无论是当前包还是外包。

type User struct {
        Name string
        code int
}

func main() {
        p := new(User)
        v := reflect.ValueOf(p).Elem()

        name := v.FieldByName("Name")
        code := v.FieldByName("code")

        fmt.Printf("name: canaddr = %v, canset = %v\n", name.CanAddr(), name.CanSet())
        fmt.Printf("code: canaddr = %v, canset = %v\n", code.CanAddr(), code.CanSet())

        if name.CanSet() {
                name.SetString("Tom")
        }

        if code.CanAddr() {
                *(*int)(unsafe.Pointer(code.UnsafeAddr())) = 100
        }

        fmt.Printf("%+v\n", *p)
}

输出:

name: canaddr = true, canset = true
code: canaddr = true, canset = false
{Name:Tom code:100}

Value.Pointer 和 Value.Int 等方法类型,将 Value.data 存储的数据转换为指针,目标必须是指针类型。而 UnsafeAddr 返回任何 CanAddr Value.data 地址(相当于 & 取地址操作),比如 Elem() 后的 Value,以及字段成员地址。

以结构体里的指针类型字段为例,Pointer 返回该字段所保存的地址,而 UnsafeAddr 返回该字段自身的地址(结构对象地址 + 偏移量)。

可通过 Interface 方法进行类型 推荐 和 转换。

func main() {
        type user struct {
                Name string
                Age  int
        }

        u := user{
                "q.yuhen",
                60,
        }

        v := reflect.ValueOf(&u)

        if !v.CanInterface() {
                println("CanInterface: fail.")
                return
        }

        p, ok := v.Interface().(*user)

        if !ok {
                println("Interface: fail.")
                return
        }

        p.Age++
        fmt.Printf("%+v\n", u)
}

输出:

{Name:q.yuhen Age:61}

也可以直接使用 Value.Int、Bool 等方法进行类型转换,但失败时会引发 pani,且不支持 ok-idiom。

复合类型对象设置示例:

func main()  {
        c := make(chan int, 4)
        v := reflect.ValueOf(c)

        if v.TrySend(reflect.ValueOf(100)) {
                fmt.Println(v.TryRecv())
        }
}

输出:

100 true

接口有两种 nil 状态,这一直是个潜在麻烦。解决方法是用 IsNil() 判断值是否为 nil。

func main()  {
        var a interface{} = nil
        var b interface{} = (*int)(nil)

        fmt.Println(a == nil)
        fmt.Println(b == nil, reflect.ValueOf(b).IsNil())
}

输出:

true
false true

也可用 unsafe 转换后直接判断 iface.data 是否为零值。

func main()  {
        var b interface{} = (*int)(nil)
        iface := (*[2]uintptr)(unsafe.Pointer(&b))

        fmt.Println(iface, iface[1] == 0)
}

输出:

&[712160 0]  true

让人很无奈的是,Value 里的某些方法并未实现 ok-idom 或返回 error,所以得自行判断返回的是否为 Zero Value。

func main()  {
        v := reflect.ValueOf(struct {name string}{})

        println(v.FieldByName("name").IsValid())
        println(v.FieldByName("xxx").IsValid())
}

输出:

true
false

三、方法

动态调用方法,谈不上有多麻烦。只须按 In 列表准备好所需参数即可。

type X struct {}

func (X) Test(x, y int) (int, error)  {
        return x + y, fmt.Errorf("err: %d", x + y)
}

func main()  {
        var a X
        v := reflect.ValueOf(&a)
        m := v.MethodByName("Test")

        in := []reflect.Value{
                reflect.ValueOf(1),
                reflect.ValueOf(2),
        }

        out := m.Call(in)
        for _, v := range out {
                fmt.Println(v)
        }
}

输出:

3
err: 3

对于变参来说,用 CallSlice() 要更方便一些。

type X struct {}

func (X) Format(s string, a ...interface{}) string {
        return fmt.Sprintf(s, a...)
}

func main() {
        var a X
        v := reflect.ValueOf(&a)
        m := v.MethodByName("Format")

        out := m.Call([]reflect.Value{
                reflect.ValueOf("%s = %d"), // 所有参数都须处理
                reflect.ValueOf("x"),
                reflect.ValueOf(100),
        })

        fmt.Println(out)

        out = m.CallSlice([]reflect.Value{
                reflect.ValueOf("%s = %d"),
                reflect.ValueOf([]interface{}{"x", 100}),
        })

        fmt.Println(out)
}

输出:

[x = 100]
[x = 100]

无法调用非导出方法,甚至无法获取有效地址。

四、构建

反射库提供了内置函数 make() 和 new() 的对应操作,其中最有意思的就是 MakeFunc()。可用它实现通用模板,适应不同数据类型。

// 通用算法函数
func add(args []reflect.Value) (results []reflect.Value) {
        if len(args) == 0 {
                return nil
        }

        var ret reflect.Value

        switch args[0].Kind() {
        case reflect.Int:
                n := 0
                for _, a := range args {
                        n += int(a.Int())
                }

                ret = reflect.ValueOf(n)
        case reflect.String:
                ss := make([]string, 0, len(args))
                for _, s := range args {
                        ss = append(ss, s.String())
                }

                ret = reflect.ValueOf(strings.Join(ss, ""))
        }

        results = append(results, ret)
        return
}

// 将函数指针参数指向通用算法函数
func makeAdd(fptr interface{}) {
        fn := reflect.ValueOf(fptr).Elem()
        v := reflect.MakeFunc(fn.Type(), add) // 这是关键
        fn.Set(v)                             // 指向通用算法函数
}

func main() {
        var intAdd func(x, y int) int
        var strAdd func(a, b string) string

        makeAdd(&intAdd)
        makeAdd(&strAdd)

        println(intAdd(100, 200))
        println(strAdd("hello, ", "world!"))
}

输出:

300
hello, world!

如果语言支持泛型,自然不需要这么折腾