func (v Value) SetInt(x int64) //设置int类型的值
func (v Value) SetUint(x uint64) // 设置无符号整型的值
func (v Value) SetFloat(x float64) // 设置浮点类型的值
func (v Value) SetComplex(x complex128) //设置复数类型的值
func (v Value) SetBool(x bool) //设置布尔类型的值
func (v Value) SetString(x string) //设置字符串类型的值
func (v Value) SetLen(n int) // 设置切片的长度,n 不能超出范围,不能为负数。
func (v Value) SetCap(n int) //设置切片的容量
func (v Value) SetBytes(x []byte) //设置字节类型的值
func (v Value) SetMapIndex(key, val reflect.Value) //设置map的key和value,前提必须是初始化以后,存在覆盖、不存在添加
##########结构体相关:
func (v Value) NumField() int // 获取结构体字段(成员)数量
func (v Value) Field(i int) reflect.Value //根据索引获取结构体字段
func (v Value) FieldByIndex(index []int) reflect.Value // 根据索引链获取结构体嵌套字段
func (v Value) FieldByName(string) reflect.Value // 根据名称获取结构体的字段,不存在返回reflect.ValueOf(nil)
func (v Value) FieldByNameFunc(match func(string) bool) Value // 根据匹配函数 match 获取字段,如果没有匹配的字段,则返回零值(reflect.ValueOf(nil))
########通道相关:
func (v Value) Send(x reflect.Value)// 发送数据(会阻塞),v 值必须是可写通道。
func (v Value) Recv() (x reflect.Value, ok bool) // 接收数据(会阻塞),v 值必须是可读通道。
func (v Value) TrySend(x reflect.Value) bool // 尝试发送数据(不会阻塞),v 值必须是可写通道。
func (v Value) TryRecv() (x reflect.Value, ok bool) // 尝试接收数据(不会阻塞),v 值必须是可读通道。
func (v Value) Close() // 关闭通道
########函数相关
func (v Value) Call(in []Value) (r []Value) // 通过参数列表 in 调用 v 值所代表的函数(或方法)。函数的返回值存入 r 中返回。
// 要传入多少参数就在 in 中存入多少元素。
// Call 即可以调用定参函数(参数数量固定),也可以调用变参函数(参数数量可变)。
func (v Value) CallSlice(in []Value) []Value // 调用变参函数
package main
import (
"reflect"
"fmt"
)
func main() {
str := "wd"
age := 11
fmt.Println(reflect.ValueOf(str).String()) //获取str的值,结果wd
fmt.Println(reflect.ValueOf(age).Int()) //获取age的值,结果age
str2 := reflect.ValueOf(&str) //获取Value类型
str2.Elem().SetString("jack") //设置值
fmt.Println(str2.Elem(),age) //jack 11
}
package main
import (
"fmt"
"reflect"
)
type Skills interface {
reading()
running()
}
type Student struct {
Name string
Age int
}
func (self Student) runing(){
fmt.Printf("%s is running\n",self.Name)
}
func (self Student) reading(){
fmt.Printf("%s is reading\n" ,self.Name)
}
func main() {
stu1 := Student{Name:"wd",Age:22}
stu_val := reflect.ValueOf(stu1) //获取Value类型
fmt.Println(stu_val.NumField()) //2
fmt.Println(stu_val.Field(0),stu_val.Field(1)) //wd 22
fmt.Println(stu_val.FieldByName("Age")) //22
stu_val2 := reflect.ValueOf(&stu1).Elem()
stu_val2.FieldByName("Age").SetInt(33) //设置字段值 ,结果33
fmt.Println(stu1.Age)
}
示例三:通过反射调用结构体中的方法,通过reflect.Value.Method(i int).Call()或者reflect.Value.MethodByName(name string).Call()实现
package main
import (
"fmt"
"reflect"
)
type Student struct {
Name string
Age int
}
func (this *Student) SetName(name string) {
this.Name = name
fmt.Printf("set name %s\n",thi