golang 反射操作
(reflection)机制
下面是一个示例:
package main
import (
\"fmt\"
\"reflect\"
)
type Person struct {
Name string
Age int
Email string
}
func (p Person) SayHello() {
fmt.Printf(\"Hello, my name is %s\\n\", p.Name)
}
func (p Person) SayEmail() {
fmt.Printf(\"My email is %s\\n\", p.Email)
}
func main() {
p := Person{
Name: \"Tom\",
Age: 28,
Email: \"tom@example.com\",
}
// 通过方法名的字符串来调用相应的方法
methodName := \"SayHello\"
method := reflect.ValueOf(p).MethodByName(methodName)
method.Call([]reflect.Value{})
methodName = \"SayEmail\"
method = reflect.ValueOf(p).MethodByName(methodName)
method.Call([]reflect.Value{})
}
运行结果:
Hello, my name is Tom
My email is tom@example.com
在上面的示例中,我们通过 reflect.ValueOf(p).MethodByName(methodName)
来获取方法的反射值。之后我们又调用了 method.Call([]reflect.Value{})
来调用这个方法。其中 []reflect.Value{}
表示方法的参数列表为空。