go语言-反射

luckyFang 2021年03月15日 62次浏览

获取类型和值

  • TypeOf
  • ValueOf
  • pair<Type,Value>
package main

import (
	"fmt"
	"reflect"
)

func main() {
	var num int =10

	fmt.Println("type:",reflect.TypeOf(num))
	fmt.Println("value:",reflect.ValueOf(num))
}

type: int
value: 10

获取字段和方法

package main

import (
	"fmt"
	"reflect"
)


type User struct {
	Name string
	Age int
}

func (this User)Invoke()  {
	fmt.Println("user method called")
}

func main() {
	var num int =10
	// 获取基础类型
	fmt.Println("type:",reflect.TypeOf(num))
	fmt.Println("value:",reflect.ValueOf(num))

	user :=User{
		Name: "Alice",
		Age:  19,
	}

	inputType := reflect.TypeOf(user)
	inputValue := reflect.ValueOf(user)

	// 遍历字段
	for i:=0;i<inputType.NumField();i++ {
		field := inputType.Field(i)
		fmt.Println("field:",field.Name,"value:",inputValue.Field(i).Interface())
	}

	// 遍历方法
	for i:=0;i<inputType.NumMethod();i++ {
		method := inputType.Method(i)
		fmt.Println("methodName:",method.Name)
	}
}

type: int
value: 10
field: Name value: Alice
field: Age value: 19
methodName: Invoke