当前位置:网站首页>Reflect reflect
Reflect reflect
2022-07-29 07:25:00 【Xiaoming's note warehouse】
The concept of reflection in programming languages
In the field of Computer Science , Reflection is a kind of application , They can describe and control themselves . in other words , This kind of application uses some mechanism to describe its behavior (self-representation) And monitoring (examination), And according to the state and result of their own behavior , Adjust or modify the state and related semantics of the behavior described by the application .
Each language has a different reflection model , And some languages don't support reflection at all .Golang Language realizes reflection , Reflection mechanism is to dynamically call the methods and properties of objects at run time , official reflect Packages are reflection related , As long as you include this package, you can use .
One more sentence ,Golang Of gRPC It is also achieved through reflection .
interface and Reflection
Before we talk about reflection , First look at it. Golang Some principles about type design
- Variables include (type, value) Two parts
- type Include
static typeandconcrete type. Simply speakingstatic typeIt's the type you see in coding ( Such as int、string),concrete typeyesruntimeThe type the system sees - Whether the type assertion can succeed , Depends on the of the variable
concrete type, instead ofstatic type. therefore , OnereaderVariable if itsconcrete typeIt has also been realized.writeMethod words , It can also be asserted by type aswriter.
What's next Reflection , Is based on type ,Golang The type of the variable of the specified type is static ( That is to designate int、string These variables , its type yes static type), It was determined when the variable was created , Reflection is mainly related to Golang Of interface Type related ( its type yes concrete type), Only interface It's the type that reflects .
stay Golang In the implementation of , Every interface Variables have a corresponding pair,pair The value and type of the actual variable are recorded in :
(value, type)value Is the actual variable value ,type Is the type of actual variable . One interface{} A variable of type contains 2 A pointer to the , A pointer to the type of value 【 Corresponding concrete type】, Another pointer points to the actual value 【 Corresponding value】.
for example , Creation type is *os.File The variable of , Then assign it to an interface variable r:
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
var r io.Reader
r = ttyInterface variables r Of pair The following information will be recorded :(tty, *os.File), This pair It is constant during the continuous assignment of interface variables , Change interface variables r Assign to another interface variable w:
var w io.Writer
w = r.(io.Writer)Interface variables w Of pair And r Of pair identical , All are :(tty, *os.File), Even if w Is an empty interface type ,pair It's the same .
interface And its pair The existence of , yes Golang The premise of realizing reflection in , I understand pair, It's easier to understand reflection . Reflection is used to detect data stored inside interface variables ( value value; type concrete type) pair A mechanism for .
package main
import (
"fmt"
"io"
"os"
)
func main() {
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
fmt.Println("open file error", err)
return
}
var r io.Reader
r = tty
var w io.Writer
w = r.(io.Writer)
w.Write([]byte("HELLO THIS IS A TEST!!!\n"))
}Another example :
package main
import "fmt"
type Reader interface {
ReadBook()
}
type Writer interface {
WriteBook()
}
// The specific type
type Book struct {
}
func (this *Book) ReadBook() {
fmt.Println("Read a book.")
}
func (this *Book) WriteBook() {
fmt.Println("Write a book.")
}
func main() {
b := &Book{}
var r Reader
r = b
r.ReadBook()
var w Writer
w = r.(Writer)
w.WriteBook()
}Golang Reflection of reflect
reflect Basic functions of TypeOf and ValueOf
Since reflection is used to detect data stored in interface variables ( value value; type concrete type) pair A mechanism for . So in Golang Of reflect What ways can we get the information inside the variable directly in the reflection package ? It provides two types ( Or two ways ) Let's easily access the contents of interface variables , Namely reflect.ValueOf() and reflect.TypeOf(), Look at the official explanation
// ValueOf returns a new Value initialized to the concrete value
// stored in the interface i. ValueOf(nil) returns the zero
func ValueOf(i interface{}) Value {...}
//ValueOf Used to obtain the value of data in the input parameter interface , If the interface is empty, return 0
// 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 {...}
//TypeOf The type used to dynamically obtain the value in the input parameter interface , If the interface is empty, return nil边栏推荐
- Full process flow of CMOS chip manufacturing
- MySQL - multi table query
- Scala higher order (IX): pattern matching in Scala
- thinkphp6 实现数据库备份
- [redis] redis development specifications and precautions
- Round avatar of user list and follow small blocks
- 0 9 布隆过滤器(Bloom Filter)
- [Charles' daily problems] when you open Charles, you can't use nails
- logback appender简介说明
- 用户列表 圆形头像并跟随小板块
猜你喜欢

用户列表 圆形头像并跟随小板块

Remote invocation of microservices

It's enough for MySQL to have this article (disgusting and crazy typing 37k words, just for Bo Jun's praise!!!)

【OpenGL】着色器(Shader)的使用
Scala higher order (IX): pattern matching in Scala

Vmware16 create virtual machine: cannot create a new virtual machine, do not have permission to perform this operation

Vmware16 create virtual machine: win11 cannot be installed

QT topic: basic components (button class, layout class, output class, input class, container class)

Docker最新超详细教程——Docker创建运行MySQL并挂载

CVPR2021| 基于自监督学习的多视图立体匹配 (CVPR2021)
随机推荐
Win11vmware turns on the virtual machine and restarts on the blue screen and the solution that cannot be started
[OpenGL] use of shaders
Spark Learning Notes (VII) -- spark core core programming - RDD serialization / dependency / persistence / partition / accumulator / broadcast variables
ETL为什么经常变成ELT甚至LET?
同步/异步、阻塞/非阻塞 与 IO
npm install 时,卡住不动,五种解决方法
gcc/g++的使用
ERROR 1045 (28000) Access denied for user ‘root‘@‘localhost‘解决方法
cdc source能读完MySqlSnapshotSplit 就退出嘛
Synchronous / asynchronous, blocking / non blocking and IO
能在SQL 语句中 指定 内存参数吗?
1-后台项目搭建
Vite3.0都发布了,你还能卷得动吗(新特性一览)
logback简介及引入方法
【WPF】通过动态/静态资源实现语言切换
Latest 10 billion quantitative private placement list
如何与斯堪尼亚SCANIA建立EDI连接?
MySQL uses the client and select methods to view the summary of blob type fields
2-统一返回类DTO对象
对Vintage分析的一些学习理解