当前位置:网站首页>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 type
andconcrete type
. Simply speakingstatic type
It's the type you see in coding ( Such as int、string),concrete type
yesruntime
The type the system sees - Whether the type assertion can succeed , Depends on the of the variable
concrete type
, instead ofstatic type
. therefore , Onereader
Variable if itsconcrete type
It has also been realized.write
Method 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 = tty
Interface 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
边栏推荐
猜你喜欢
Summary of OCR optical character recognition methods
Some learning and understanding of vintage analysis
js中break与continue和return关键字
CVPR2021| 基于自监督学习的多视图立体匹配 (CVPR2021)
QT basic day 2 (2) QT basic components: button class, layout class, output class, input class, container and other individual examples
dba
Personal blog system (with source code)
Docker最新超详细教程——Docker创建运行MySQL并挂载
彻底搞懂kubernetes调度框架与插件
JS day 4 process control (if statement and switch statement)
随机推荐
Section 7 - compilation of programs (preprocessing operations) + links
Cvpr2021 | multi view stereo matching based on self supervised learning (cvpr2021)
Does Flink support sqlserver databases? Get the changes of SQLSERVER database
1-后台项目搭建
Vmware16 create virtual machine: cannot create a new virtual machine, do not have permission to perform this operation
Fillder use
能在SQL 语句中 指定 内存参数吗?
mysql 单表最多能存多少数据?
Gin routing, parameters, output
Spingboot integrates the quartz framework to realize dynamic scheduled tasks (support real-time addition, deletion, modification and query tasks)
Clock tree synthesis (I)
QT专题:基础部件(按钮类,布局类,输出类,输入类,容器类)
论文阅读 (62):Pointer Networks
After three years of outsourcing, the salary of automatic testing after job hopping is twice that of the original. The secret is
What is the function of fileappender in logback?
个人博客系统(附源码)
SpingBoot整合Quartz框架实现动态定时任务(支持实时增删改查任务)
CMOS芯片制造全工艺流程
2022-07-28: what is the output of the following go language code? A:AA; B:AB; C:BA; D:BB。 package main import ( “fmt“ ) func main() { f
zip gzip tar压缩进阶版