简单的获取值或设置值
func getV() {
f := 3.14
v := reflect.ValueOf(&f)
newf := v.Interface().(float64)
fmt.Println(newf)
}
func setV() {
f := 3.14
v := reflect.ValueOf(&f)
if v.Elem().CanSet() && v.Elem().CanAddr() {
v.Elem().SetFloat(4.13)
} else {
fmt.Println("not")
}
fmt.Println(f)
}
调用结构体方法
type Student struct {
sid string
}
func (s *Student) EchoS(args ...string) {
fmt.Println(s.sid)
for _, arg := range args {
fmt.Println(arg)
}
}
func main() {
s := &Student{sid: "2019"}
v := reflect.ValueOf(s)
method := v.MethodByName("EchoS")
if method.IsValid() {
args := []reflect.Value{reflect.ValueOf("li"), reflect.ValueOf("yi")}
method.Call(args)
} else {
fmt.Println("not found")
}
}
由接口到方法
func makeRfFunc(f interface{}) interface{} {
tp := reflect.TypeOf(f)
vp := reflect.ValueOf(f)
if tp.Kind() != reflect.Func {
fmt.Println("not Func")
return nil
}
fc := reflect.MakeFunc(tp, func(args []reflect.Value) (results []reflect.Value) {
fmt.Println("i m reflect.makefunc")
res := vp.Call(args)
return res
})
return fc.Interface()
}
func main() {
f := func(a, b string) {
fmt.Println("a", a, "b", b)
}
resFunc := makeRfFunc(f).(func(string, string))
resFunc("b", "a")
}
其他关于字段与方法
func (Value) NumField
func (v Value) NumField() int
返回v持有的结构体类型值的字段数,如果v的Kind不是Struct会panic
func (Value) NumMethod
func (v Value) NumMethod() int
返回v持有值的方法集的方法数目。