Getting a List of Method Names from an Interface
In Go, reflection allows for inspecting and manipulating the internal structure of a program at runtime. This includes the ability to access information about an interface type, such as its method names.
Consider the following interface:
type FooService interface {
Foo1(x int) int
Foo2(x string) string
}
To obtain a list of the method names for this interface using reflection:
t := reflect.TypeOf((*FooService)(nil)).Elem()
This line retrieves the reflect.Type for the concrete type that implements the FooService interface.
for i := 0; i The NumMethod() function returns the number of methods in the interface.
- Get the method names:
s = append(s, t.Method(i).Name)
The Method(i) function returns a reflect.Method object representing the method at index i. The Name field of this object contains the name of the method.
The resulting list s will contain the method names ["Foo1", "Foo2"].
Explanations:
- The (*FooService)(nil) syntax is used to create a pointer to an anonymous instance of the FooService interface. This is necessary to obtain the reflect.Type for the interface.
- The Elem() method returns the reflect.Type for the concrete type that implements the interface, instead of the interface type itself.
- The NumMethod() function returns the number of methods declared in the interface, even if the concrete type implements additional methods.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3