I'm writing small and very DRY framework, which heavily relies on metadata. I'd like to know if there is a way to obtain method parameter names, i.e. given some method
public void a(int myIntParam, String theString) { ... }
get the strings "myIntParam"
and "theString"
.
I know I could annotate parameters, but that wouldn't be nice...
public void a(
@Param("myIntParam") int myIntParam,
@Param("theString") String theString
) { ... }
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.
We learned that parameter passing in Java is always Pass-by-Value. However, the context changes depending upon whether we're dealing with Primitives or Objects: For Primitive types, parameters are pass-by-value.
Here is a dirty solution that needs some tweaking. Maybe someone can make it better.
import com.sun.org.apache.bcel.internal.classfile.ClassParser;
import com.sun.org.apache.bcel.internal.classfile.JavaClass;
import com.sun.org.apache.bcel.internal.classfile.LocalVariable;
import com.sun.org.apache.bcel.internal.classfile.Method;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
ClassParser parser = new ClassParser("Main.class");
JavaClass clazz = parser.parse();
for (Method m : clazz.getMethods()) {
System.out.println("Method: " + m.getName());
int size = m.getArgumentTypes().length;
if (!m.isStatic()) {
size++;
}
for (int i = 0; i < size; i++) {
LocalVariable variable = m.getLocalVariableTable().getLocalVariable(i);
System.out.println(" - Param: " + variable.getName());
}
}
}
public void a(int myIntParam, String theString) {
}
}
$ javac -g Main.java
$ java Main
Method: <init>
- Param: this
Method: main
- Param: args
Method: a
- Param: this
- Param: myIntParam
- Param: theString
I could be wrong about this... but I don't think parameter names appear in a class file so I would guess that there is no way to get them via reflection.
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