go语言(十五)----reflect

package main

import (
	"fmt"
	"reflect"
)

type User struct {
   
	Id int
	Name string
	Age int
}

func (this *User) Call() {
   

	fmt.Println("user is called...")
	fmt.Println("%v\n",this)

}




func main() {
   
	user := User{
   1,"AceId",18}
	DoFileAndMethod(user)
}

func DoFileAndMethod(input interface{
   }) {
   

	//获取input的type
	intputType := reflect.TypeOf(input)
	fmt.Println("inputType is:",intputType)
	//获取input的value
	inputValue := reflect.ValueOf(input)
	fmt.Println("inputValue is :",inputValue)


	//通过type获取里面的字段
	//1、获取interface的reflect.type,通过Type得到Numfiled,进行遍历
	//2、得到每个field,数据类型
	//3、通过field有一个Interface()方法得到对应的value
	for i :=0;i<intputType.NumField();i++ {
   
		field := intputType.Field(i)
		value := inputValue.Field(i).Interface()
		fmt.Printf("%s: %v = %v\n",field,field.Type,value)
	}

	//通过Type获取里面的 方法,调用
	for i :=0;i < intputType.NumMethod();i++ {
   
		m := intputType.Method(i)
		fmt.Println("%s: %v\n",m.Name,m.Type)

	}
}

在这里插入图片描述

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-01-25 00:52:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-25 00:52:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-25 00:52:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-25 00:52:01       20 阅读

热门阅读

  1. 论文素材:PSO算法介绍

    2024-01-25 00:52:01       37 阅读
  2. mysql单表查询练习题

    2024-01-25 00:52:01       36 阅读
  3. 在 Spring Boot 中使用事务

    2024-01-25 00:52:01       34 阅读
  4. 【nginx】405 not allowed问题解决方法

    2024-01-25 00:52:01       42 阅读
  5. linux 之 ln 命令

    2024-01-25 00:52:01       35 阅读
  6. c语言之循环语句练习

    2024-01-25 00:52:01       37 阅读
  7. 更改ip后还被封是ip质量的原因吗?

    2024-01-25 00:52:01       38 阅读
  8. jquery笔记

    2024-01-25 00:52:01       32 阅读
  9. 【Webpack】样式处理 - 分离样式文件

    2024-01-25 00:52:01       33 阅读
  10. python

    2024-01-25 00:52:01       36 阅读
  11. 240124

    240124

    2024-01-25 00:52:01      33 阅读