Go中(reflect)结构体反射

104 阅读1分钟

获取struct中的变量信息

package main

import (
	"fmt"
	"reflect"
)

type student struct {
	Name  string `json:"name" ini:"s_name"`
	Score int    `json:"score" ini:"s_score"`
}

func main() {

	stu1 := student{
		Name:  "Jay",
		Score: 85,
	}

	//通过反射去获取结构体中的所有字段信息
	t := reflect.TypeOf(stu1)
	//遍历结构体变量的所有字段
	for i := 0; i < t.NumField(); i++ {
		//根据结构体字段所引去获取字段
		fileObj := t.Field(i)
		fmt.Printf("name: %v type:%v tag:%v \n", fileObj.Name, fileObj.Type, fileObj.Tag)
		//输出字段tag中的json
		fmt.Printf("fileObj.Tag.Get(\"json\"): %v\n", fileObj.Tag.Get("json"))
		//输出字段tag中的ini
		fmt.Printf("fileObj.Tag.Get(\"ini\"): %v\n", fileObj.Tag.Get("ini"))
	}

	// 通过字段名获取指定结构体字段信息
	if scoreField, ok := t.FieldByName("Name"); ok {
		fmt.Printf("name:%s index:%d type:%v json tag:%v\n", scoreField.Name, scoreField.Index, scoreField.Type, scoreField.Tag.Get("json"))
	}

}

name: Name type:string tag:json:"name" ini:"s_name" fileObj.Tag.Get("json"): name fileObj.Tag.Get("ini"): s_name name: Score type:int tag:json:"score" ini:"s_score" fileObj.Tag.Get("json"): score fileObj.Tag.Get("ini"): s_score name:Score index:[1] type:int json tag:score

获取struct中的方法

package main

import (
	"fmt"
	"reflect"
)

type student struct {
	Name  string `json:"name" ini:"s_name"`
	Score int    `json:"score" ini:"s_score"`
}

// 给student添加两个方法 Study和Sleep(注意首字母大写)
func (s student) Study(name interface{}) string {

	//name.(string) :将interface{} 转为string
	msg := name.(string) + "要好好学习,天天向上。"
	fmt.Println(msg)
	return msg
}

func (s student) Sleep(name interface{}) string {
	msg := name.(string) + "要好好睡觉,快快长大。"
	fmt.Println(msg)
	return msg
}

func printMethod(x interface{}) {
	t := reflect.TypeOf(x)
	v := reflect.ValueOf(x)

	fmt.Println(t.NumMethod())
	for i := 0; i < v.NumMethod(); i++ {
		methodType := v.Method(i).Type()
		fmt.Printf("method name:%s\n", t.Method(i).Name)
		fmt.Printf("method:%s\n", methodType)
		// 通过反射调用方法传递的参数必须是 []reflect.Value 类型
		// var args = []reflect.Value{} 函数无参时使用
		args := []reflect.Value{reflect.ValueOf("Jone")}
		//通过call()方法去调用函数
		v.Method(i).Call(args)
	}
}

func main() {

	stu := student{
		Name:  "Jay",
		Score: 85,
	}

	printMethod(stu)

}
2
method name:Sleep
method:func(interface {}) string
Jone要好好睡觉,快快长大。
method name:Study
method:func(interface {}) string
Jone好好学习,天天向上。