golang的反射机制(三)
通过反射来进行方法的调用
1、对象实例:
package main
import (
"fmt"
"reflect"
)
//通过反射来进行方法的调用
type Person struct {
Name string
Age int
Sex string
}
func (p Person) Say(msg string,i int) {
fmt.Printf("hello,%s,%d\n",msg,i)
}
func (p Person) PrintInfo() {
fmt.Printf("姓名:%s,年龄:%d,性别:%s\n",p.Name,p.Age,p.Sex)
}
func main() {
/*
通过反射来进行方法的调用
思路:1、接口变量-->对象反射对象:Value
2、获取对应的方法对象:MethodByName()
3、将方法对象进行调用:Call()
*/
//一、
p1 := Person{"老李",30,"男"}
value:=reflect.ValueOf(p1)
fmt.Printf("kind : %s, type : %s\n",value.Kind(),value.Type())//kind : struct, type : main.Person
methodValue1:=value.MethodByName("PrintInfo")
fmt.Printf("kind:%s,type:%s\n",methodValue1.Kind(),methodValue1.Type())//kind:func,type:func()
//没有参数,进行调用
methodValue1.Call(nil)//姓名:老李,年龄:30,性别:男
//或者传一个空切片也可以
args1:=make([]reflect.Value,0)
methodValue1.Call(args1) //姓名:老李,年龄:30,性别:男
//二、
methodValue2:=value.MethodByName("Say")
fmt.Printf("kind:%s,type:%s\n",methodValue2.Kind(),methodValue2.Type()) //kind:func,type:func(string, int)
args2:=[]reflect.Value{reflect.ValueOf("反射机制"),reflect.ValueOf(100)}
methodValue2.Call(args2) //hello,反射机制,100
}
2、普通函数实例
package main
import (
"fmt"
"reflect"
"strconv"
)
//函数反射
func main() {
/*
思路:函数也可以看作接口变量类型
1、函数-->反射对象,Value
2、kind-->func
3、call()
*/
f1:=fun1
value1:=reflect.ValueOf(f1)
fmt.Printf("kind : %s, type : %s\n",value1.Kind(),value1.Type())
value2:=reflect.ValueOf(fun2)
value3:=reflect.ValueOf(fun3)
fmt.Printf("kind : %s, type : %s\n",value2.Kind(),value2.Type())
fmt.Printf("kind : %s, type : %s\n",value3.Kind(),value3.Type())
//通过反射调用函数
value1.Call(nil)
value2.Call([]reflect.Value{reflect.ValueOf(100),reflect.ValueOf("张三")})
resultValue:=value3.Call([]reflect.Value{reflect.ValueOf(200),reflect.ValueOf("李四")})
fmt.Printf("%T\n",resultValue)
fmt.Println(len(resultValue))
fmt.Printf("kind:%s,type:%s\n",resultValue[0].Kind(),resultValue[0].Type())
s:=resultValue[0].Interface().(string)
fmt.Println(s)
fmt.Printf("%T\n",s)
}
func fun1() {
fmt.Println("我是fun1(),无参")
}
func fun2(i int,s string) {
fmt.Println("我是fun2(),有参..",i,s)
}
func fun3(i int,s string)string {
fmt.Println("我是fun3(),有参,有返回值",i,s)
return s+strconv.Itoa(i)
}