Go语言反射执行结构体方法教程

reflect.ValueOf()

通过反射的 MethodByName 获取的方法只能获取导出的方法,也就是首字母大写的方法。

Go语言反射调用结构体方法

语法

personValue := reflect.ValueOf(p) infoFunc := personValue.MethodByName("Info") infoFunc.Call([]reflect.Value{})

说明

通过 reflect.ValueOf 获取结构体的值信息,再次使用结构体值信息的 MethodByName 获取结构体的方法,最后使用 Call 方法可以实现调用结构体的方法。

案例

Go语言反射调用结构体方法

通过 Go 语言反射调用结构体方法

package main import ( "fmt" "reflect" ) type Student struct { Name string Age int Score float64 } func (s Student)Info(){ fmt.Println("Name =", s.Name, "Age =", s.Age, "Score =", s.Score) } func main() { fmt.Println("嗨客网(www.haicoder.net)") var p = Student{ Name:"HaiCoder", Age:10, Score:99, } personValue := reflect.ValueOf(p) infoFunc := personValue.MethodByName("Info") infoFunc.Call([]reflect.Value{}) }

程序运行后,控制台输出如下:

27_golang反射调用方法.png

首先,我们定义了一个 Student 结构体,并且给 Student 结构体添加了一个可导出的 Info 方法,该方法实现打印 Student 结构体的类信息。

reflect.ValueOf

Go语言反射调用结构体带参数和返回值的方法

通过 Go 语言反射调用结构体带参数和返回值的方法

package main import ( "fmt" "reflect" ) type Student struct { Name string Age int Score float64 } // 定义一个结构体,并为结构体添加带参数和返回值的方法 func (s Student)IsPass(score float64)(isPass bool){ if s.Score >= score{ return true } return false } func main() { fmt.Println("嗨客网(www.haicoder.net)") var p = Student{ Name:"HaiCoder", Age:10, Score:99, } personValue := reflect.ValueOf(p) IsPassFunc := personValue.MethodByName("IsPass") args := []reflect.Value{reflect.ValueOf(100.0)} res := IsPassFunc.Call(args) fmt.Println("Pass =", res[0].Bool()) args = []reflect.Value{reflect.ValueOf(60.0)} res = IsPassFunc.Call(args) fmt.Println("Pass =", res[0].Bool()) }

程序运行后,控制台输出如下:

28_golang反射调用方法.png

首先,我们定义了一个 Student 结构体,并且给 Student 结构体添加了一个可导出的 IsPass 方法,该方法实现判断传入的参数是否大于结构体初始化的值,并返回 的结果。

最后,我们通过 reflect.ValueOf 组装需要通过反射调用的方法的参数,并使用 res 接受返回值,并通过 res 数组的索引加上返回的对应的数据类型来获取返回值。

Go语言反射执行结构体方法总结

reflect.ValueOf()

通过反射的 MethodByName 获取的方法只能获取导出的方法,也就是首字母大写的方法。