golang reflection calling method

WBOY
Release: 2023-05-15 10:28:37
Original
1044 people have browsed it

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
Copy after login

}

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)
Copy after login

}

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)
Copy after login

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")
Copy after login

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())
Copy after login

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
Copy after login
Copy after login

}

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

type FlashDisk struct {

Name string
Copy after login
Copy after login

}

func (f *FlashDisk) Connect() error {

fmt.Printf("%s 连接成功
Copy after login
Copy after login

", f.Name)

return nil
Copy after login
Copy after login
Copy after login
Copy after login

}

func (f *FlashDisk) Disconnect() error {

fmt.Printf("%s 断开连接
Copy after login
Copy after login

", f.Name)

return nil
Copy after login
Copy after login
Copy after login
Copy after login

}

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)
Copy after login

}

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

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

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)
Copy after login

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"
Copy after login

)

type UsbDevice interface {

Connect() error
Disconnect() error
Copy after login
Copy after login

}

type FlashDisk struct {

Name string
Copy after login
Copy after login

}

func (f *FlashDisk) Connect() error {

fmt.Printf("%s 连接成功
Copy after login
Copy after login

", f.Name)

return nil
Copy after login
Copy after login
Copy after login
Copy after login

}

func (f *FlashDisk) Disconnect() error {

fmt.Printf("%s 断开连接
Copy after login
Copy after login

", f.Name)

return nil
Copy after login
Copy after login
Copy after login
Copy after login

}

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)
Copy after login

}

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!