Go 语言提供了一种机制在运行时更新变量和检查它们的值、调用它们的方法,但是在编译时并不知道这些变量的具体类型,这称为反射机制。
funcmain(){var x float64=3.1415
fmt.Println(reflect.TypeOf(x))
fmt.Println(reflect.ValueOf(x))
fmt.Println("=====================================")
v := reflect.ValueOf(x)
fmt.Println(v.Kind()== reflect.Float64)
fmt.Println("type:", v.Type())
fmt.Println("value:", v.Float())}
二.reflect获取接口变量信息
例子(一)
funcmain(){var num float64=4.31
v := reflect.ValueOf(num)
convertValue := v.Interface().(float64)
fmt.Println(convertValue)
fmt.Println("-------------------------------")
v1 := reflect.ValueOf(&num)
convertValue1 := v1.Interface().(*float64)
fmt.Println(convertValue1)
fmt.Println(*convertValue1)}
例子(二)
funcmain(){var p person = person{
Name:"zzs",
Age:10,
Sex:false,}GetMessage(p)}type person struct{
Name string
Age int
Sex bool}func(p person)Say(msg string){
fmt.Println("hello!", msg)}func(p person)PrintInfo(){
fmt.Printf("姓名:%s,年龄:%d,性别:%v", p.Name, p.Age, p.Sex)}funcGetMessage(value interface{}){
getType := reflect.TypeOf(value)
fmt.Println(getType.Name())
fmt.Println(getType.Kind())
getValue := reflect.ValueOf(value)
fmt.Println(getValue)
fmt.Println(getType.NumField())
fmt.Println(getValue.NumField())//获取结构体中的字段for i :=0; i < getValue.NumField(); i++{
field := getType.Field(i)
v := getValue.Field(i).Interface()
fmt.Println(field.Name)
fmt.Println(field.Type)
fmt.Println(v)}//获取结构体中的方法
fmt.Println(getType.NumMethod())for i :=0; i < getType.NumMethod(); i++{
method := getType.Method(i)
fmt.Println(method.Name, method.Type)}}
type Student struct{
Name string
Age int
Sex bool}funcmain(){
s1 := Student{"zzs",18,false}
value := reflect.ValueOf(&s1)if value.Kind()== reflect.Ptr {
newValue := value.Elem()
fmt.Println(newValue.CanSet())
f1 := newValue.FieldByName("Name")
f1.SetString("ywj")
f2 := newValue.FieldByName("Age")
f2.SetInt(19)
f3 := newValue.FieldByName("Sex")
f3.SetBool(true)
fmt.Println(s1)}}
四.reflect对象调用方法和函数
例子(一)
type MyPerson struct{
Name string
Age int
Sex bool}func(m MyPerson)SayHello(){
fmt.Println("Hello!")}func(m MyPerson)Print(msg string){
fmt.Println(m.Name, msg)}funcmain(){
p := MyPerson{
Name:"zzs",
Age:18,
Sex:false,}
v := reflect.ValueOf(p)
m1 := v.MethodByName("SayHello")
m1.Call(nil)
m2 := v.MethodByName("Print")
slice :=[]reflect.Value{reflect.ValueOf("zzs")}
m2.Call(slice)}