首页 星云 工具 资源 星选 资讯 热门工具
:

PDF转图片 完全免费 小红书视频下载 无水印 抖音视频下载 无水印 数字星空

深入探究 Golang 反射:功能与原理及应用

编程知识
2024年07月21日 15:10

Hi 亲爱的朋友们,我是 k 哥。今天,咱们来一同探讨下 Golang 反射。

Go 出于通用性的考量,提供了反射这一功能。借助反射功能,我们可以实现通用性更强的函数,传入任意的参数,在函数内通过反射动态调用参数对象的方法并访问它的属性。举例来说,下面的bridge接口为了支持灵活调用任意函数,在运行时根据传入参数funcPtr,通过反射动态调用funcPtr指向的具体函数。

func bridge(funcPtr interface{}, args ...interface{})

再如,ORM框架函数为了支持处理任意参数对象,在运行时根据传入的参数,通过反射动态对参数对象赋值。

type User struct {
        Name string
        Age  int32
}
user := User{}
db.FindOne(&user)

本文将深入探讨Golang反射包reflect的功能和原理。同时,我们学习某种东西,一方面是为了实践运用,另一方面则是出于功利性面试的目的。所以,本文还会为大家介绍反射的典型应用以及高频面试题。

1 关键功能

reflect包提供的功能比较多,但核心功能是把interface变量转化为反射类型对象reflect.Type和reflect.Value,并通过反射类型对象提供的功能,访问真实对象的方法和属性。本文只介绍3个核心功能,其它方法可看官方文档。

1.对象类型转换。通过TypeOf和ValueOf方法,可以将interface变量转化为反射类型对象Type和Value。通过Interface方法,可以将Value转换回interface变量。

type any = interface{}

// 获取反射对象reflect.Type
// TypeOf returns the reflection Type that represents the dynamic type of i. 
// If i is a nil interface value, TypeOf returns nil.
func TypeOf(i any) Type

// 获取反射对象reflect.Value
// ValueOf returns a new Value initialized to the concrete value stored in the interface i. 
// ValueOf(nil) returns the zero Value.
func ValueOf(i any) Value

// 反射对象转换回interface
func (v Value) Interface() (i any)

示例如下:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    age := 18
    fmt.Println("type: ", reflect.TypeOf(age)) // 输出type:  int
    value := reflect.ValueOf(age)
    fmt.Println("value: ", value) // 输出value:  18

    fmt.Println(value.Interface().(int)) // 输出18
}

2.变量值设置。通过reflect.Value的SetXX相关方法,可以设置真实变量的值。reflect.Value是通过reflect.ValueOf(x)获得的,只有当x是指针的时候,才可以通过reflec.Value修改实际变量x的值。

// Set assigns x to the value v. It panics if Value.CanSet returns false. 
// As in Go, x's value must be assignable to v's type and must not be derived from an unexported field.
func (v Value) Set(x Value)
func (v Value) SetInt(x int64)
...

// Elem returns the value that the interface v contains or that the pointer v points to. It panics if v's Kind is not Interface or Pointer. It returns the zero Value if v is nil.
func (v Value) Elem() Value

示例如下:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    age := 18
    // 通过reflect.ValueOf获取age中的reflect.Value
    // 参数必须是指针才能修改其值
    pointerValue := reflect.ValueOf(&age)
    // Elem和Set方法结合,相当于给指针指向的变量赋值*p=值
    newValue := pointerValue.Elem()
    newValue.SetInt(28)
    fmt.Println(age) // 值被改变,输出28

    // reflect.ValueOf参数不是指针
    pointerValue = reflect.ValueOf(age)
    newValue = pointerValue.Elem() // 如果非指针,直接panic: reflect: call of reflect.Value.Elem on int Value
}

3.方法调用。Method和MethodByName可以获取到具体的方法,Call可以实现方法调用。

// Method returns a function value corresponding to v's i'th method. 
// The arguments to a Call on the returned function should not include a receiver; 
// the returned function will always use v as the receiver. Method panics if i is out of range or if v is a nil interface value.
func (v Value) Method(i int) Value

// MethodByName returns a function value corresponding to the method of v with the given name.
func (v Value) MethodByName(name string) Value

// Call calls the function v with the input arguments in. For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]). 
// Call panics if v's Kind is not Func. It returns the output results as Values
func (v Value) Call(in []Value) []Value

示例如下:

package main

import (
    "fmt"
    "reflect"
)

type User struct {
    Age int
}

func (u User) ReflectCallFunc(name string) {
    fmt.Printf("age %d ,name %+v\n", u.Age, name)
}

func main() {
    user := User{18}

    // 1. 通过reflect.ValueOf(interface)来获取到reflect.Value
    getValue := reflect.ValueOf(user)

    methodValue := getValue.MethodByName("ReflectCallFunc")
    args := []reflect.Value{reflect.ValueOf("k哥")}
    // 2. 通过Call调用方法
    methodValue.Call(args) // 输出age 18 ,name k哥
}

2 原理

Go语言反射是建立在Go类型系统和interface设计之上的,因此在聊reflect包原理之前,不得不提及Go的类型和interface底层设计。

2.1 静态类型和动态类型

在Go中,每个变量都会在编译时确定一个静态类型。所谓静态类型(static type),就是变量声明时候的类型。比如下面的变量i,静态类型是interface

var i interface{}

所谓动态类型(concrete type,也叫具体类型),是指程序运行时系统才能看见的,变量的真实类型。比如下面的变量i,静态类型是interface,但真实类型是int

var i interface{}   

i = 18 

2.2 interface底层设计

对于任意一个静态类型是interface的变量,Go运行时都会存储变量的值和动态类型。比如下面的变量age,会存储值和动态类型(18, int)

var age interface{}
age = 18

2.3 reflect原理

reflect是基于interface实现的。通过interface底层数据结构的动态类型和数据,构造反射对象。

reflect.TypeOf获取interface底层的动态类型,从而构造出reflect.Type对象。通过Type,可以获取变量包含的方法、字段等信息。

// TypeOf returns the reflection Type that represents the dynamic type of i.
// If i is a nil interface value, TypeOf returns nil.
func TypeOf(i interface{}) Type {
    eface := *(*emptyInterface)(unsafe.Pointer(&i)) // eface为interface底层结构
    return toType(eface.typ) // eface.typ就是interface底层的动态类型
}

func toType(t *rtype) Type {
    if t == nil {
        return nil
    }
    return t
}

reflect.ValueOf获取interface底层的Type和数据,封装成reflect.Value对象。

type Value struct {
    // typ holds the type of the value represented by a Value.
    typ *rtype // 动态类型

    // Pointer-valued data or, if flagIndir is set, pointer to data.
    // Valid when either flagIndir is set or typ.pointers() is true.
    ptr unsafe.Pointer // 数据指针

    // flag holds metadata about the value.
    // The lowest bits are flag bits:
    //  - flagStickyRO: obtained via unexported not embedded field, so read-only
    //  - flagEmbedRO: obtained via unexported embedded field, so read-only
    //  - flagIndir: val holds a pointer to the data
    //  - flagAddr: v.CanAddr is true (implies flagIndir)
    //  - flagMethod: v is a method value.
    // The next five bits give the Kind of the value.
    // This repeats typ.Kind() except for method values.
    // The remaining 23+ bits give a method number for method values.
    // If flag.kind() != Func, code can assume that flagMethod is unset.
    // If ifaceIndir(typ), code can assume that flagIndir is set.
    flag // 标记位,用于标记此value是否是方法、是否是指针等

}

type flag uintptr

// ValueOf returns a new Value initialized to the concrete value
// stored in the interface i. ValueOf(nil) returns the zero Value.
func ValueOf(i interface{}) Value {
    if i == nil {
        return Value{}
    }
    return unpackEface(i)
}

// unpackEface converts the empty interface i to a Value.
func unpackEface(i interface{}) Value {
    // interface底层结构
    e := (*emptyInterface)(unsafe.Pointer(&i))
    // NOTE: don't read e.word until we know whether it is really a pointer or not.
    // 动态类型
    t := e.typ
    if t == nil {
        return Value{}
    }
    // 标记位,用于标记此value是否是方法、是否是指针等
    f := flag(t.Kind())
    if ifaceIndir(t) {
        f |= flagIndir
    }
    return Value{t, e.word, f} // t为类型,e.word为数据,
}

3 应用

工作中,反射常见应用场景有以下两种:

1.不知道接口调用哪个函数,根据传入参数在运行时通过反射调用。例如以下这种桥接模式:

package main

import (
    "fmt"
    "reflect"
)

// 函数内通过反射调用funcPtr
func bridge(funcPtr interface{}, args ...interface{}) {
    n := len(args)
    inValue := make([]reflect.Value, n)
    for i := 0; i < n; i++ {
        inValue[i] = reflect.ValueOf(args[i])
    }
    function := reflect.ValueOf(funcPtr)
    function.Call(inValue)
}

func call1(v1 int, v2 int) {
    fmt.Println(v1, v2)
}
func call2(v1 int, v2 int, s string) {
    fmt.Println(v1, v2, s)
}
func main() {
    bridge(call1, 1, 2)         // 输出1 2
    bridge(call2, 1, 2, "test") // 输出1 2 test
}

2.不知道传入函数的参数类型,函数需要在运行时处理任意参数对象,这种需要对结构体对象反射。典型应用场景是ORM,orm示例如下:

package main

import (
    "fmt"
    "reflect"
)

type User struct {
    Name string
    Age  int32
}

func FindOne(x interface{}) {
    sv := reflect.ValueOf(x)
    sv = sv.Elem()
    // 对于orm,改成从db里查出来再通过反射设置进去
    sv.FieldByName("Name").SetString("k哥")
    sv.FieldByName("Age").SetInt(18)
}

func main() {
    user := &User{}
    FindOne(user)
    fmt.Println(*user) // 输出 {k哥 18}
}

4 高频面试题

1.reflect(反射包)如何获取字段 tag?

通过反射包获取tag。步骤如下:

  1. 通过reflect.TypeOf生成反射对象reflect.Type

  2. 通过reflect.Type获取Field

  3. 通过Field访问tag

package main

import (
    "fmt"
    "reflect"
)

type User struct {
    Name string `json:"name" otherTag:"name"`
    age  string `json:"age"`
}

func main() {
    user := User{}
    userType := reflect.TypeOf(user)
    field := userType.Field(0)
    fmt.Println(field.Tag.Get("json"), field.Tag.Get("otherTag")) // 输出name name

    field = userType.Field(1)
    fmt.Println(field.Tag.Get("json")) // 输出age
}


2.为什么 json 包不能导出私有变量的 tag?

从1中的例子中可知,反射可以访问私有变量age的tag。json包之所以不能导出私有变量,是因为json包的实现,将私有变量的tag跳过了。

func typeFields(t reflect.Type) structFields {
    // Scan f.typ for fields to include.
    for i := 0; i < f.typ.NumField(); i++ {
        sf := f.typ.Field(i)
        // 非导出成员(私有变量),忽略tag
        if !sf.IsExported() {
            // Ignore unexported non-embedded fields.
            continue
        }
        tag := sf.Tag.Get("json")
        if tag == "-" {
            continue
        }          
    }
}

3.json包里使用的时候,结构体里的变量不加tag能不能正常转成json里的字段?

  1. 如果是私有成员,不能转,因为json包会忽略私有成员的tag信息。比如下面的demo中,User结构体中的a和b都不能json序列化。

  2. 如果是公有成员。

  • 不加tag,可以正常转为json里的字段,json的key跟结构体内字段名一致。比如下面的demo,User中的C序列化后,key和结构体字段名保持一致是C。
  • 加了tag,从struct转json的时候,json的key跟tag的值一致。比如下面的demo,User中的D序列化后是d。
package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    a string // 小写无tag
    b string `json:"b"` //小写+tag
    C string //大写无tag
    D string `json:"d"` //大写+tag
}

func main() {
    u := User{
        a: "1",
        b: "2",
        C: "3",
        D: "4",
    }
    fmt.Printf("%+v\n", u) // 输出{a:1 b:2 C:3 D:4}
    jsonInfo, _ := json.Marshal(u)
    fmt.Printf("%+v\n", string(jsonInfo)) // 输出{"C":"3","d":"4"}
}

From:https://www.cnblogs.com/killianxu/p/18314594
本文地址: http://www.shuzixingkong.net/article/248
0评论
提交 加载更多评论
其他文章 Nuxt 使用指南:掌握 useNuxtApp 和运行时上下文
title: Nuxt 使用指南:掌握 useNuxtApp 和运行时上下文 date: 2024/7/21 updated: 2024/7/21 author: cmdragon excerpt: 摘要:“Nuxt 使用指南:掌握 useNuxtApp 和运行时上下文”介绍了Nuxt 3中useN
Nuxt 使用指南:掌握 useNuxtApp 和运行时上下文 Nuxt 使用指南:掌握 useNuxtApp 和运行时上下文
一文揭开JDK21虚拟线程的神秘面纱
虚拟线程快速体验 环境:JDK21 + IDEA public static void main(String[] args) { try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { IntStream.range(0
番外2: go语言写的简要数据同步工具
go-etl工具 作为go-etl工具的作者,想要安利一下这个小巧的数据同步工具,它在同步百万级别的数据时表现极为优异,基本能在几分钟完成数据同步。 1.它能干什么的? go-etl是一个数据同步工具集,目前支持MySQL,postgres,oracle,SQL SERVER,DB2等主流关系型数据
番外2: go语言写的简要数据同步工具 番外2: go语言写的简要数据同步工具 番外2: go语言写的简要数据同步工具
数据库的性能调优:如何正确的使用索引?
在当今的数据驱动时代,数据库的性能优化成为每个开发者和数据库管理员必须掌握的技能之一。而在众多优化手段中,索引的使用无疑是最为重要和有效的。然而,索引的滥用或误用不仅不会提升性能,反而可能带来额外的开销。那么,如何正确地使用索引,才能真正提升数据库性能呢? 为什么有时我们精心创建的索引却没有带来预期
数据库的性能调优:如何正确的使用索引? 数据库的性能调优:如何正确的使用索引? 数据库的性能调优:如何正确的使用索引?
设计模式之观察者模式(学习笔记)
定义 观察者模式是一种行为型设计模式,它定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会收到通知并自动更新。这种模式用于实现对象之间的解耦,使得一个对象的变化可以通知并更新多个依赖对象,而无需直接引用它们。 为什么使用观察者模式? 解耦 观察者模式将观察者(Observ
试试这个工作流引擎吧,还有个简洁美观的流程设计器
ruoyi-flow若依工作流引擎设计器一个简洁轻量的工作流引擎。 java工作流引擎,真正的国产工作流引擎,前后端代码完整且还拥有一个简洁美观的流程设计器。 前端vue后端Java的。 功能特点 1、使用json存储流程模板 2、支持驳回、拿回等 3、支持状态配置、权限配置 4、支持条件分支 流程
试试这个工作流引擎吧,还有个简洁美观的流程设计器 试试这个工作流引擎吧,还有个简洁美观的流程设计器 试试这个工作流引擎吧,还有个简洁美观的流程设计器
ComfyUI进阶:Comfyroll插件 (六)
ComfyUI进阶:Comfyroll插件 (六)前言:学习ComfyUI是一场持久战,而Comfyroll 是一款功能强大的自定义节点集合,专为 ComfyUI 用户打造,旨在提供更加丰富和专业的图像生成与编辑工具。借助这些节点,用户可以在静态图像的精细调整和动态动画的复杂构建方面进行深入探索。C
ComfyUI进阶:Comfyroll插件 (六) ComfyUI进阶:Comfyroll插件 (六) ComfyUI进阶:Comfyroll插件 (六)
方法引用
方法引用有什么用? 写更少代码 提高代码复用性和可维护性(尤其是团队项目中) 引用静态方法如果你要引用的是一个静态方法,你可以使用类名::静态方法的形式。例如, 将集合中String类型数据转换成int类型这是匿名内部类的写法:查看parsInt源码可以发现该方法满足静态方法引用的条件.因此可以直接
方法引用 方法引用 方法引用