go语言反射处理

  • TypeOf
  • ValueOf
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package main

import (
	"fmt"
	"reflect"
)
 
func main() {
	i := 1
	t := (reflect.TypeOf(i))
	fmt.Println(reflect.TypeOf(t))
}

调用结构体方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
	"fmt"
	"reflect"
)

func main() {
	hl := func() {
		fmt.Println("hello world")
	}
	fv := reflect.ValueOf(hl)
	fmt.Println("fv is reflect.Func ?", fv.Kind() == reflect.Func)
	fv.Call(nil)
}
/*
PS D:\ASUS\Desktop\temp\golang学习> go run .\main.go
fv is reflect.Func ? true
hello world
PS D:\ASUS\Desktop\temp\golan

*/

根据方法名字调用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main

import (
	"fmt"
	"reflect"
)

type Foo struct {
	One string
	Two int
}

func (f Foo) CallFuncNoArgs() {
	fmt.Printf("One is: %s, Two is: %d\n", f.One, f.Two)

}
func (f Foo) CallFuncWithArgs(name string, a int) {
	fmt.Printf("name:%s a:%d\n", name, a)
}

func (f Foo) CallFuncWithArgsAndRet(one, two int) (int, string) {
	fmt.Printf("one:%d two:%d\n", one, two)
	return one + two, "CallFuncWithArgsAndRet string"
}

func main() {
	var foo = &Foo{"Award", 666}
	// 方法名必须大写
	// if name not FuncName will panic  reflect: call of reflect.Value.Call on zero Value
	reflect.ValueOf(foo).MethodByName("CallFuncNoArgs").Call([]reflect.Value{})

	in := make([]reflect.Value, 2)
	in[0] = reflect.ValueOf("Colin")
	in[1] = reflect.ValueOf(111)
	_ = reflect.ValueOf(foo).MethodByName("CallFuncWithArgs").Call(in)

	in[0] = reflect.ValueOf(1)
	in[1] = reflect.ValueOf(2)
	values := reflect.ValueOf(foo).MethodByName("CallFuncWithArgsAndRet").Call(in)
	//fmt.Printf("return value:%v\n", value[0].Interface().(int))
	for _, value := range values {
		fmt.Printf("value:%v\n", value)
	}
}

反射赋值,修改结构体

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import (
	"fmt"
	"reflect"
)

type D struct {
	ID int
}

func main() {
	m := D{5}
	s := reflect.ValueOf(&m).Elem()
	s.Field(0).SetInt(77)
	fmt.Println(m.ID)

}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
type T struct {
    Age int
    Name string
    Children []int
}
t := T{12, "someone-life", nil}
s := reflect.ValueOf(&t).Elem()

s.Field(0).SetInt(123) // 内置常用类型的设值方法
sliceValue := reflect.ValueOf([]int{1, 2, 3}) // 这里将slice转成reflect.Value类型
s.FieldByName("Children").Set(sliceValue)

作者:life
链接:https://www.zhihu.com/question/22783511/answer/24960616
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。