GoLang 反射

GoLang 反射,第1张

GoLang 反射 一.反射初识
  • Go 语言提供了一种机制在运行时更新变量和检查它们的值、调用它们的方法,但是在编译时并不知道这些变量的具体类型,这称为反射机制。
func main() {
	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获取接口变量信息 例子(一)
func main() {
	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)
}
例子(二)
func main() {
	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)
}
func GetMessage(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)
	}
}
三.reflect对象设置实际变量的值
  • 如果要修改值的话,需要传递引用
例子(一)
func main() {
	var num float64 = 32.18
	pointer := reflect.ValueOf(&num)
	newValue := pointer.Elem()
	fmt.Println(newValue.Type())
	fmt.Println(newValue.CanSet())

	newValue.SetFloat(3.14)
	fmt.Println(num)
}
例子(二)
type Student struct {
	Name string
	Age  int
	Sex  bool
}

func main() {
	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)
}

func main() {
	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)
}
例子(二)
func main() {
	m1 := reflect.ValueOf(fun1)
	m1.Call(nil)

	m2 := reflect.ValueOf(fun2)
	m2.Call([]reflect.Value{reflect.ValueOf("zzs"), reflect.ValueOf(18)})

	m3 := reflect.ValueOf(fun3)
	slice := m3.Call([]reflect.Value{reflect.ValueOf("zzs")})
	fmt.Println(slice)
}

func fun1() {
	fmt.Println("无参无返回...")
}

func fun2(str string, num int) {
	fmt.Println("有参无返回", str, num)
}

func fun3(str string) (string, string) {
	fmt.Println("有参有返回:", str)
	return "zzs", "ywj"
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/793474.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-06
下一篇 2022-05-06

发表评论

登录后才能评论

评论列表(0条)

保存