Go反射四讲---第一讲:什么是反射,反射常用的API,反射三原则以及注意事项

2024-08-25 10:28

本文主要是介绍Go反射四讲---第一讲:什么是反射,反射常用的API,反射三原则以及注意事项,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

反射-引入

这是我们反射四讲的第一讲,本次主要向大家介绍一下反射的基础概念以及相关的API。

在计算机科学中,反射是指计算机程序能够在运行时可以访问,检测和修改本身状态或者行为的一种能力。

简单的来说,反射就是程序在运行时能够动地查看自己的状态,并允许修改自身的行为。

首先,要明白对于一个类型变量。它有两层含义,一是类型是什么,二是存储的值是什么。类型决定了变量的存储方式,支持的操作和方法等。值无外乎是读与写,在存储是以0,1格式存放,并使用类型加以约束。类型和值不是孤立存在的。

反射的相关API都在 reflect 包中,最核心的就是reflect.Valuereflect.Type
其中,reflect.Value用于操作值,部分值是可以被反射修改的。reflect.Type用于操作类型信息。类型信息是只能读取的。

注意:reflect.Type可以通过reflect.Value得到,但是反过来不行。

reflect.Type

func TypeOf(i any) Type
//type any = interface{}

形参是一个空接口类型,返回值是一个 Type 接口类型。

注意:reflect包有一个很强的的假设,我们必须我们要操作的是什么Kind

Kind是一个枚举值,用来判断操作的对应类型。例如是否是指针,是否是数组,是否是切片等。
如果使用不当就会引起 panic。so,在调用API之前,我们一定要先读注释,确认什么情况下可以使用!!!

接下来,讲解一下 Type 接口提供的主要通用方法。

类型的通用方法

// Name returns the type's name within its package for a defined type.
Name() string// Kind returns the specific kind of this type.
Kind() Kind// Implements reports whether the type implements the interface type u.
Implements(u Type) bool// AssignableTo reports whether a value of the type is assignable to type u.
AssignableTo(u Type) bool// ConvertibleTo reports whether a value of the type is convertible to type u.
ConvertibleTo(u Type) bool// Comparable reports whether values of this type are comparable.
Comparable() bool// NumMethod returns the number of methods accessible using Method.
NumMethod() int// Method returns the i'th method in the type's method set.
Method(int) Method// MethodByName returns the method with that name in the type's
// method set and a boolean indicating if the method was found.
MethodByName(string) (Method, bool)// PkgPath returns a defined type's package path, that is, the import path
PkgPath() string// Size returns the number of bytes needed to store
Size() uintptr

类型的专有方法

type Type interface {
// Elem returns a type's element type.
// It panics if the type's Kind is not Array, Chan, Map, Pointer, or Slice.
Elem() Type// Bits returns the size of the type in bits.
Bits() int// Len returns an array type's length.
// It panics if the type's Kind is not Array.
Len() int// struct 专有的方法// NumField returns a struct type's field count.
// It panics if the type's Kind is not Struct.
NumField() int// Field returns a struct type's i'th field.
// It panics if the type's Kind is not Struct.
// It panics if i is not in the range [0, NumField()).
Field(i int) StructField// FieldByIndex returns the nested field corresponding
// to the index sequence. It is equivalent to calling Field
// successively for each index i.
// It panics if the type's Kind is not Struct.
FieldByIndex(index []int) StructField// FieldByName returns the struct field with the given name
// and a boolean indicating if the field was found.
// If the returned field is promoted from an embedded struct,
// then Offset in the returned StructField is the offset in
// the embedded struct.
FieldByName(name string) (StructField, bool)// FieldByNameFunc returns the struct field with a name
// that satisfies the match function and a boolean indicating if
// the field was found.
FieldByNameFunc(match func(string) bool) (StructField, bool)// func 专有的方法// IsVariadic reports whether a function type's final input parameter
// IsVariadic panics if the type's Kind is not Func.
IsVariadic() bool// In returns the type of a function type's i'th input parameter.
// It panics if the type's Kind is not Func.
// It panics if i is not in the range [0, NumIn()).
In(i int) Type// NumIn returns a function type's input parameter count.
// It panics if the type's Kind is not Func.
NumIn() int// NumOut returns a function type's output parameter count.
// It panics if the type's Kind is not Func.
NumOut() int// map 专有的方法// Key returns a map type's key type.
// It panics if the type's Kind is not Map.
Key() Type
}

reflect.Value

reflect.Value 表示的是实例的值信息。reflect.Value是一个 struct,并且提供了一系列的 method

func ValueOf(i any) Value
//type Value struct {
//	typ_ *abi.Type  //值的指针类型typ
//	ptr unsafe.Pointer // 指向值的指针ptr
//	flag //标记字段
//}

注意:这里一定要搞清与Type的区别,Type 直接返回接口,Value 返回的是结构体,而在结构体上绑定了一些方法。

下面我们介绍几个常用的在 Value 结构体上绑定的方法。

// CanAddr reports whether the value's address can be obtained with [Value.Addr].
func (v Value) CanAddr() bool {}// Addr returns a pointer value representing the address of v.
func (v Value) Addr() Value {}// CanSet reports whether the value of v can be changed.
func (v Value) CanSet() bool {}// Elem returns the value that the interface v contains
// or that the pointer v points to.
func (v Value) Elem() Value {}// Field returns the i'th field of the struct v.
func (v Value) Field(i int) Value {}// Bool returns v's underlying value.
func (v Value) Bool() bool {}// Bytes returns v's underlying value.
func (v Value) Bytes() []byte {} // Index returns v's i'th element.
func (v Value) Index(i int) Value {}

这里方法我们没有讲解全面,如果想了解源码内容,可以去 reflect 包下的 value.go 下查看。

反射的原则

下图展示了实例,Type与Value三者之间的关系。

API使用总结:

  1. 实例到 Value。使用实例获取对象的 Value,直接使用 reflect.ValueOf() 函数。

  2. 实例到 Type。使用实例获取对象的 Type, 直接使用 reflect.TypeOf()函数。

  3. TypeValue。无法直接从一个 Type 接口变量获取实例的 Value。一般先使用 Type 构建一个新的实例Value

    第一种,使用func New(typ Type) Value创建一个ValueValueType是一个指定的typ的指针类型。

    第二种,使用func Zero(typ Type) Value创建一个Value,注意此时的Value不能寻址,意味着值不可以变。

    第三种,如果知道一个值的底层存放地址,可以使用func NewAt(typ Type, p unsafe.Pointer) Value来恢复Value。此处的typ是实例类型,p是实例的地址。

  4. ValueType。直接可以调用Value结构体上绑定的func (v Value) Type() Type {}方法。

  5. Value 到实例。可以使用通用方法func (v Value) Interface() (i any) {}直接返回实例。

  6. Value指针到值。使用func (v Value) Elem() Value {}返回值。注意:如果类型是接口,则 Elem()返回接口绑定的实例的 Value ,如果类型是指针,则返回指针值的 Value ,否则引起 panic

  7. Type指针到Type值。使用Elem() Type返回子元素的Type

  8. Type值到Type指针。使用func PtrTo(t Type) Type {},返回指向t的指针类型Type

  9. 值的可修改性。可以使用func (v Value) CanSet() bool {}去判断一个值是否可以修改,如果可以修改返回true。接着可以使用func (v Value) Set(x Value)去设置一个值。

总结

本次,带领大家了解反射的基本概念,如何使用等。待熟悉相关的API之后,下一次,我们将展示给您如何在实战中使用reflect包。

参考

  • 《Go语言核心编程》-- 李文塔
  • https://pkg.go.dev/reflect

这篇关于Go反射四讲---第一讲:什么是反射,反射常用的API,反射三原则以及注意事项的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1105302

相关文章

C#中读取XML文件的四种常用方法

《C#中读取XML文件的四种常用方法》Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具,下面我们就来看看C#中读取XML文件的方法都有哪些吧... 目录XML简介格式C#读取XML文件方法使用XmlDocument使用XmlTextReader/XmlTextWr

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

SpringBoot中使用 ThreadLocal 进行多线程上下文管理及注意事项小结

《SpringBoot中使用ThreadLocal进行多线程上下文管理及注意事项小结》本文详细介绍了ThreadLocal的原理、使用场景和示例代码,并在SpringBoot中使用ThreadLo... 目录前言技术积累1.什么是 ThreadLocal2. ThreadLocal 的原理2.1 线程隔离2

Go路由注册方法详解

《Go路由注册方法详解》Go语言中,http.NewServeMux()和http.HandleFunc()是两种不同的路由注册方式,前者创建独立的ServeMux实例,适合模块化和分层路由,灵活性高... 目录Go路由注册方法1. 路由注册的方式2. 路由器的独立性3. 灵活性4. 启动服务器的方式5.

Deepseek R1模型本地化部署+API接口调用详细教程(释放AI生产力)

《DeepseekR1模型本地化部署+API接口调用详细教程(释放AI生产力)》本文介绍了本地部署DeepSeekR1模型和通过API调用将其集成到VSCode中的过程,作者详细步骤展示了如何下载和... 目录前言一、deepseek R1模型与chatGPT o1系列模型对比二、本地部署步骤1.安装oll

浅析如何使用Swagger生成带权限控制的API文档

《浅析如何使用Swagger生成带权限控制的API文档》当涉及到权限控制时,如何生成既安全又详细的API文档就成了一个关键问题,所以这篇文章小编就来和大家好好聊聊如何用Swagger来生成带有... 目录准备工作配置 Swagger权限控制给 API 加上权限注解查看文档注意事项在咱们的开发工作里,API

Go语言中三种容器类型的数据结构详解

《Go语言中三种容器类型的数据结构详解》在Go语言中,有三种主要的容器类型用于存储和操作集合数据:本文主要介绍三者的使用与区别,感兴趣的小伙伴可以跟随小编一起学习一下... 目录基本概念1. 数组(Array)2. 切片(Slice)3. 映射(Map)对比总结注意事项基本概念在 Go 语言中,有三种主要

CSS弹性布局常用设置方式

《CSS弹性布局常用设置方式》文章总结了CSS布局与样式的常用属性和技巧,包括视口单位、弹性盒子布局、浮动元素、背景和边框样式、文本和阴影效果、溢出隐藏、定位以及背景渐变等,通过这些技巧,可以实现复杂... 一、单位元素vm 1vm 为视口的1%vh 视口高的1%vmin 参照长边vmax 参照长边re

一分钟带你上手Python调用DeepSeek的API

《一分钟带你上手Python调用DeepSeek的API》最近DeepSeek非常火,作为一枚对前言技术非常关注的程序员来说,自然都想对接DeepSeek的API来体验一把,下面小编就来为大家介绍一下... 目录前言免费体验API-Key申请首次调用API基本概念最小单元推理模型智能体自定义界面总结前言最

Java通过反射获取方法参数名的方式小结

《Java通过反射获取方法参数名的方式小结》这篇文章主要为大家详细介绍了Java如何通过反射获取方法参数名的方式,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、前言2、解决方式方式2.1: 添加编译参数配置 -parameters方式2.2: 使用Spring的内部工具类 -