Given the following Go method:
func (t *T) TMethod(data *testData) (interface{}, *error) {
...
}
I want to reflect the name of the parameter (which is data
here).
I tried the following, but it returns the structure name (which is testData
here):
reflect.ValueOf(T).MethodByName("TMethod").Type().In(0).Elem().Name()
How can I get the name of the parameter?
getting parameter type is possible, using method. getParameterTypes()
You can obtain the names of the formal parameters of any method or constructor with the method java. lang. reflect.
Full Stack Java developer - Java + JSP + Restful WS + Spring Following is a generic example which uses getParameterNames() method of HttpServletRequest to read all the available form parameters. This method returns an Enumeration that contains the parameter names in an unspecified order.
To call a method in Java, simply write the method's name followed by two parentheses () and a semicolon(;). If the method has parameters in the declaration, those parameters are passed within the parentheses () but this time without their datatypes specified.
There is no way to get the names of the parameters of a method or a function.
The reason for this is because the names are not really important for someone calling a method or a function. What matters is the types of the parameters and their order.
A Function type denotes the set of all functions with the same parameter and result types. The type of 2 functions having the same parameter and result types is identical regardless of the names of the parameters. The following code prints true
:
func f1(a int) {}
func f2(b int) {}
fmt.Println(reflect.TypeOf(f1) == reflect.TypeOf(f2))
It is even possible to create a function or method where you don't even give names to the parameters (within a list of parameters or results, the names must either all be present or all be absent). This is valid code:
func NamelessParams(int, string) {
fmt.Println("NamelessParams called")
}
For details and examples, see Is unnamed arguments a thing in Go?
If you want to create some kind of framework where you call functions passing values to "named" parameters (e.g. mapping incoming API params to Go function/method params), you may use a struct
because using the reflect
package you can get the named fields (e.g. Value.FieldByName()
and Type.FieldByName()
), or you may use a map
. See this related question: Initialize function fields
Here is a relevant discussion on the golang-nuts mailing list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With