一个简单的java中的反射机制代码
时间: 2024-05-11 08:17:09 浏览: 13
以下是一个简单的 Java 反射机制代码:
```java
import java.lang.reflect.Method;
public class ReflectionDemo {
public static void main(String[] args) {
try {
// 获取 Class 对象
Class<?> clazz = Class.forName("java.lang.String");
// 获取指定方法
Method method = clazz.getMethod("equals", Object.class);
// 输出方法信息
System.out.println("方法名称:" + method.getName());
System.out.println("返回类型:" + method.getReturnType());
System.out.println("修饰符:" + method.getModifiers());
System.out.println("参数个数:" + method.getParameterCount());
} catch (ClassNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}
```
这个代码通过获取 `java.lang.String` 类的 `equals` 方法,然后输出了该方法的名称、返回类型、修饰符和参数个数。使用反射可以在运行时获取类的信息、调用方法和操作属性等。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)