JAVA 如何反射获取方法的参数对象
时间: 2024-03-14 17:44:38 浏览: 29
可以使用Java的反射机制中的Method类中的getParameters()方法来获取方法的参数对象,例如:
```java
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
public class ReflectionExample {
public void exampleMethod(String name, int age) {
// method body here
}
public static void main(String[] args) {
Class<?> clazz = ReflectionExample.class;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println("Method name: " + method.getName());
Parameter[] parameters = method.getParameters();
for (Parameter parameter : parameters) {
System.out.println("Parameter name: " + parameter.getName());
System.out.println("Parameter type: " + parameter.getType());
System.out.println("Parameter object: " + parameter);
}
}
}
}
```
这段代码使用反射获取了ReflectionExample类中所有方法的参数对象,并打印出来。其中,getMethod()方法可以获取指定名称和参数类型的方法,getDeclaredMethod()方法可以获取所有声明的方法。而getParameters()方法可以获取方法的参数对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)