当前位置:网站首页>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边栏推荐
- QT basic day 2 (2) QT basic components: button class, layout class, output class, input class, container and other individual examples
- Operator3 - design an operator
- 能在SQL 语句中 指定 内存参数吗?
- MySQL 使用客户端以及SELECT 方式查看 BLOB 类型字段内容总结
- 论文阅读 (62):Pointer Networks
- 3-global exception handling
- How to use GS_ Expansion expansion node
- Introduction to logback filter
- Scala 高阶(十):Scala中的异常处理
- Leetcode 209. subarray with the smallest length (2022.07.28)
猜你喜欢
随机推荐
npm install报错npm ERR Could not resolve dependency npm ERR peer
Levelfilter introduction
What is the function of fileappender in logback?
Clock tree synthesis (I)
zip gzip tar压缩进阶版
Summer summary (II)
I'd like to ask, my flick job writes data in the way of upsert Kafka, but I'm more careful in MySQL
Life cycle hooks in routing - activated and deactivated
After three years of outsourcing, the salary of automatic testing after job hopping is twice that of the original. The secret is
彻底搞懂kubernetes调度框架与插件
How to use GS_ Expansion expansion node
Error 1045 (28000) access denied for user 'root' @ 'localhost' solution
【Unity实战100例】Unity万能答题系统之单选多选判断题全部通用
JS break and continue and return keywords
Some learning and understanding of vintage analysis
How much data can a single MySQL table store at most?
作业7.28 文件IO与标准IO
Custom events
It's enough for MySQL to have this article (disgusting and crazy typing 37k words, just for Bo Jun's praise!!!)
Comparison of advantages between can & canfd integrated test analysis software lkmaster and PCA Explorer 6 analysis software









