Home >Backend Development >Golang >golang reflection calling method

golang reflection calling method

WBOY
WBOYOriginal
2023-05-15 10:28:371220browse

Preface

In Golang, the reflection mechanism is an important function. It can dynamically obtain the type and value of variables at runtime, and can dynamically call methods, especially for some general-purpose The reflection mechanism is indispensable for the implementation of specific code and the implementation of some frameworks.

This article will use an example to introduce how to use reflection calling methods in Golang.

Introduction to reflection calling method

The reflection calling method refers to dynamically calling the object's function at runtime. Through the reflection package, you can dynamically obtain the object at runtime and call the object's method. Of course, before calling the method through reflection, we need to perform necessary processing on the object type, method name, method parameter type, etc.

In Go, we can use the reflect package to perform reflection call methods. This package mainly provides the following important methods:

  • reflect.ValueOf: Get the reflection of the object Value object;
  • reflect.TypeOf: Get the reflection type object of the object;
  • reflect.MethodByName: Get the reflection method object of the specified type object based on the method name;
  • Method. Call: Call a method and return the result.

Basic reflection call method example

Let us look at a basic reflection call method example.

Suppose we have a structure type Person:

type Person struct {

Name string
Age  int

}

Now we want to call the GetName method of the Person structure , but we don’t know the type of the object. At this time, we need to use the reflect package to implement the reflection calling method.

First, we need to create a Person object and get its reflection value object:

func main() {

person := &Person{Name: "Alice", Age: 18}
value := reflect.ValueOf(person)

}

reflect.ValueOf( person) returns a value of type reflect.Value, which is a pointer value pointing to the structure type of the object. We can use the following code to obtain the type of the object:

typ := reflect.TypeOf(person)

In this way we successfully obtain After obtaining the reflection value object and reflection type object of the object, next we need to obtain the reflection method object of the GetName method. The code is as follows:

method := value.MethodByName("GetName")

If there is no GetName method in the object, the method will return zero value reflect.Value{ }.

Now that we have obtained the reflection method object of the method, we can call the method and get the return value:

res := method.Call(nil)
fmt.Println(res[0].String())

To call a method, you need to use the Call method, which accepts a parameter list ( reflect.Value slice type) and returns a list of values ​​of the slice type. Since the GetName method does not pass in parameters, we can pass in a nil slice.

Complete example of reflection calling method

Now that we have understood how to use reflection to call basic methods, we will learn the reflection calling method in more depth through a complete example.

We define a UsbDevice interface, which contains two methods, namely Connect and Disconnect:

type UsbDevice interface {

Connect() error
Disconnect() error

}

We will Define a FlashDisk type and implement two methods of the UsbDevice interface:

type FlashDisk struct {

Name string

}

func (f *FlashDisk) Connect() error {

fmt.Printf("%s 连接成功

", f.Name)

return nil

}

func (f *FlashDisk) Disconnect() error {

fmt.Printf("%s 断开连接

", f.Name)

return nil

}

Now we need to use reflection to dynamically call the FlashDisk type method.

First, we need to create a FlashDisk object and get its reflection value object:

func main() {

flashDisk := &FlashDisk{Name: "闪迪 U 盘"}
value := reflect.ValueOf(flashDisk)

}

Next, we You need to obtain the reflection method object of the Connect and Disconnect methods:

connectMethod := value.MethodByName("Connect")
disconnectMethod := value.MethodByName("Disconnect")

Note that here we need to ensure that the Connect and Disconnect methods exist in the object, otherwise the reflection method object obtained here will return the zero value reflect.Value{}.

Next, we use the Call method to call these two methods:

connectRes := connectMethod.Call(nil)
disconnectRes := disconnectMethod.Call(nil)

When calling the Call method, you need to pass in a parameter list. Since the Connect and Disconnect methods have no parameters, we can pass Enter a nil slice.

The complete code is as follows:

package main

import (

"fmt"
"reflect"

)

type UsbDevice interface {

Connect() error
Disconnect() error

}

type FlashDisk struct {

Name string

}

func (f *FlashDisk) Connect() error {

fmt.Printf("%s 连接成功

", f.Name)

return nil

}

func (f *FlashDisk) Disconnect() error {

fmt.Printf("%s 断开连接

", f.Name)

return nil

}

func main() {

flashDisk := &FlashDisk{Name: "闪迪 U 盘"}
fmt.Println("使用反射调用方法:")
value := reflect.ValueOf(flashDisk)

connectMethod := value.MethodByName("Connect")
disconnectMethod := value.MethodByName("Disconnect")

connectRes := connectMethod.Call(nil)
disconnectRes := disconnectMethod.Call(nil)

fmt.Println(connectRes)
fmt.Println(disconnectRes)

}

Run the above program, the output result is:

Use reflection calling method:
SanDisk U disk connection successful
[]
[]

So far, we have successfully used reflection to call the Connect and Disconnect methods of the FlashDisk type.

Summary

This article demonstrates how to use reflection to call methods through a complete example, mainly using the ValueOf, TypeOf, MethodByName and Call methods in the reflect package. We can use these methods to dynamically obtain the value, type, method, etc. of the object, and dynamically call the object's method at runtime. It should be noted that the reflection calling method must first ensure that the specified method exists in the object, otherwise the call will return a zero value reflect.Value{}. Reflection calling methods are very useful in certain situations and can help us implement some common code implementations and framework implementations.

The above is the detailed content of golang reflection calling method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn